Saravanan666/pypi-org huggingface dataset:
Package: decorator
The goal of the decorator module is to make it easy to define
signature-preserving function decorators and decorator factories.
It also includes an implementation of multiple dispatch and other niceties
(please check the docs). It is released under a two-clauses
BSD license, i.e. basically you can do whatever you want with it but I am not
responsible.InstallationIf you are lazy, just perform$ pip install decoratorwhich will install just the module on your system.If you prefer to install the full distribution from source, including
the documentation, clone theGitHub repoor download thetarball, unpack it and run$ pip install .in the main directory, possibly as superuser.TestingIf you have the source code installation you can run the tests with$ python src/tests/test.py -vor (if you have setuptools installed)$ python setup.py testNotice that you may run into trouble if in your system there
is an older version of the decorator module; in such a case remove the
old version. It is safe even to copy the moduledecorator.pyover
an existing one, since we kept backward-compatibility for a long time.RepositoryThe project is hosted on GitHub. You can look at the source here:https://github.com/micheles/decoratorDocumentationThe documentation has been moved tohttps://github.com/micheles/decorator/blob/master/docs/documentation.mdFrom there you can get a PDF version by simply using the print
functionality of your browser.Here is the documentation for previous versions of the module:https://github.com/micheles/decorator/blob/4.3.2/docs/tests.documentation.rsthttps://github.com/micheles/decorator/blob/4.2.1/docs/tests.documentation.rsthttps://github.com/micheles/decorator/blob/4.1.2/docs/tests.documentation.rsthttps://github.com/micheles/decorator/blob/4.0.0/documentation.rsthttps://github.com/micheles/decorator/blob/3.4.2/documentation.rstFor the impatientHere is an example of how to define a family of decorators tracing slow
operations:fromdecoratorimportdecorator@decoratordefwarn_slow(func,timelimit=60,*args,**kw):t0=time.time()result=func(*args,**kw)dt=time.time()-t0ifdt>timelimit:logging.warn('%stook%dseconds',func.__name__,dt)else:logging.info('%stook%dseconds',func.__name__,dt)returnresult@warn_slow# warn if it takes more than 1 minutedefpreprocess_input_files(inputdir,tempdir):...@warn_slow(timelimit=600)# warn if it takes more than 10 minutesdefrun_calculation(tempdir,outdir):...Enjoy!
Package: decorator-cli
dclidcliis a nested functional-oriented cli (command line interface) python module.dclidoes not require any other third-party module, it just wraps and encapsolutesargparsein a decorator, i.e.@dcli.command().Getting StartedBefore installing, seeRequirementsto check the dependencies.SeeInstallationto installdclito your local environment andUsagefor more information about how to use.RequirementsWhiledclidoes not require any third-party, it requires run in Python with specific versions.above Python 3.9InstallationOnly one step to installdcli:$python3-mpipinstalldecorator-cli# pip list to check installation$python3-mpiplist

PackageVersion
----------------------
decorator-cli<version>UsageTo create our own command, just type following code:importdcli...@dcli.command("MyCommand",dcli.arg(...),dcli.arg(...),...)defMyCommand(namespace):......# call the command function directly to parse the arguments from program.MyCommand()namespacewhich is of typeargparse.Namespacewill be passed fromArgumentParser.parse_args(). We can directly callMyCommand()without any parameters to parse the program arguments and then the original functionMyCommand(namespace)will be invoked onceparse_args()done. For advanced usage, it is possible to pass parameterargsintoMyCommand()to parse custom arguments, e.g.MyCommand('--baz')MyCommand(['-x','X'])MyCommand(['--foo','bar'])dclialso support subcommand:@dcli.command("COMMAND_NAME",dcli.arg(...),dcli.arg(...),...,parent=MyCommand)defSubCommand(namespace):...MyCommand()The above code will makeSubCommandbe a subcommand inMyCommandand named inCOMMAND_NAME. By callingMyCommand(["COMMAND_NAME"]), we can easily triggerSubCommand(namespace)and do what we want.
Package: decorator-http
decorator-httpTo simplify handling HTTP requests in Python, you can utilize thedecorator-httppackage, which allows you to employ decorators for various HTTP methods. Begin by installing the package using the following pip command:pipinstalldecorator-httpNow, let's explore how to use this package with different HTTP methods:GETfromdecorator_httpimportget@get('https://some-website.com',headers={'Content-Type':'application/json'})defget_example(data=None,response=None,error=None):iferror:print('Failed to request details:',error)returnprint('Response data:',data)print('Response status:',response.status_code)get_example()Handling ErrorsYou can handle errors by checking theerrorparameter within the decorator function. If an error occurs, it will be passed to the function, allowing you to handle it accordingly.@get('https://wrong-website.com',headers={'Content-Type':'application/json'})defget_example(data=None,response=None,error=None):iferror:print('Failed to request details:',error)returnprint('Response data:',data)print('Response status:',response.status_code)get_example()POSTfromdecorator_httpimportpost,put,delete@post('https://some-website.com',body={"hello":"world"},headers={'Content-Type':'application/json'})defpost_example(data=None,response=None,error=None):iferror:print('Error:',error)returnprint('Response data:',data)print('Response status:',response.status_code)post_example()Example for PUT and DELETEFor PUT and DELETE requests, you can use the respective decorators in a similar manner. Here's an example for DELETE:@delete('https://some-website.com',headers={'Content-Type':'application/json'})defdelete_example(data=None,response=None,error=None):iferror:print('Error:',error)returnprint('Response data:',data)print('Response status:',response.status_code)delete_example()Similarly, you can use@putfor PUT requests following a comparable structure.
Package: decorator-libs
1. pip install decorator_libs各种最常用的日常通用不针对具体业务的装饰器大全

包括普通任意实现的装饰器
例如单例模式 享元模式 函数结果缓存装饰器。

和非常好玩但难实现的装饰器
例如where_is_it_called和pysnooper_click_able 装饰器。

上下文管理器：
自动捕获错误的
自动统计代码片段消耗时间的
redis分布式锁上下文
Package: decorator-retry
A simple decorator for retry functions@retry(ValueError,KeyError,retry=True,attempts=3,wait=1,reraise=True,logger=logging.debug)deffunc():passDecorator parametersexceptionsSPECIFIEDexception types.retryif retry is True , retry when the decorated function throws theSPECIFIEDexceptions.if retry is False , retry when the decorated function throws theUNSPECIFIEDexceptions.Default is True.attemptsThe number of retries attempted. Default is 3.waitThe wait interval between retries (second).Default is 1 second.reraiseIf reraise is True, when an exception is thrown by the decorated function, that exception will be rethrown. If raraise is False, then None is returned instead.Default is True.loggerThe logger function will be used when the decorated function raise exception.
Default is logging.warning.
Package: decorators
DecoratorsThe problemPython has a few forms for decorators, you can have a plain simple decorator, with no arguments:@mydecoratordeffoo():passOr a decorator with some arguments:@mydecorator(1,2)deffoo():passYou can even decorate a class:@mydecoratorclassFoo(object):passand each form is a little different to implement. This was frustrating if you wanted to create easy to use decorators where the developer didn't need to worry about@mydecorator()working differently than@mydecorator.decorators moduleThedecorators.Decoratorclass allows you to easily create broad decorators that encompass all forms and all types (functions, methods, classes) using the same interface:importdecoratorsclassmydecorator(decorators.Decorator):defdecorate_func(self,func,*dec_args,**dec_kwargs):defdecorator(*args,*kwargs):print("You passed into the decorator these arguments",dec_args,dec_kwargs)print("You passed into your function these arguments",args,kwargs)print("Your function is",func)returnfunc(*args,**kwargs)returndecoratordefdecorate_class(self,klass,*dec_args,**dec_kwargs):print("You passed into the decorator these arguments",dec_args,dec_kwargs)print("Your class is",klass)returnklassYou can then use this decorator:@mydecoratordeffoo():print"foo()"@mydecorator(1,2,boom="blam")defbar(*args,**kwargs):print"bar()"@mydecoratorclassBaz(object):pass@mydecorator(1,2,boom="blam")classChe(object):passNow, your decorator can decorate functions or classes, pass in arguments, or not, and you never have to worry about the subtle differences between the decorators, and best of all, you don't have to duplicate code.Other decoratorsFuncDecorator, ClassDecorator, and InstanceDecoratorTheDecoratorclass is good if you want to create a decorator that is totally flexible, if you want to enforce your decorator only being used for a function/method, you can useFuncDecorator. If you want to only decorate a class, useClassDecorator, and if you want to decorate every instance of a class, useInstanceDecorator.Whatever child class you use, you override thedecoratemethod to return your decorator function:importdecoratorsclassonly_func(FuncDecorator):defdecorate(self,func,*dec_a,**dec_kw):defdecorator(*args,**kwargs):returnfunc(*args,**kwargs)returndecorator# this will work@only_funcdeffoo():pass# this will fail@only_funcclassFoo(object):passProperty DecoratorThepropertydecorator is a drop-in replacement for Python's built-inpropertydecorator, with additional functionality:fromdecoratorsimportpropertyclassFoo(object):@propertydefbar(self):"""This will act just like python's built-in @property decorator"""return1@property(cached="_che")defche(self):"""This will cache the return value into _che and add a setter/deleter"""return1Classproperty DecoratorAllows you to create a property on the class:fromdecoratorsimportclasspropertyclassFoo(object):@classpropertydefbar(cls):"""Available as Foo.bar"""return1print(Foo.bar)# 1InstallationUse pip:pip install decoratorsOr, to get the latest and greatest from source:pip install -U "git+https://github.com/Jaymon/decorators#egg=decorators"
Package: decorators-cryptography
decorators-cryptographydecorators-cryptography is a Python library that provides decorators for encrypting and decrypting passed arguments using the cryptography package.Contents:Installing Poetry and running the virtual environmentInstall PoetryStart virtual environmentInstall pre-commit hooksInstall pre-commitInstall pre-commit hooksExample UsageInstalling Poetry and running the virtual environmentℹ️Poetry DocumentationInstall PoetryFor Linux, macOS, Windows (WSL):curl-sSLhttps://install.python-poetry.org|python3-For Windows (Powershell):(Invoke-WebRequest-Urihttps://install.python-poetry.org-UseBasicParsing).Content|py-On macOS and Windows, the installation script will prompt you to add the Poetry executable folder to the PATH variable. Do this by running the following command (don't forget to change {USERNAME} to your username):macOSexportPATH="/Users/{USERNAME}/.local/bin:$PATH"Windows$Env:Path+=";C:\Users\{USERNAME}\AppData\Roaming\Python\Scripts";setxPATH"$Env:Path"Check installation:poetry--versionInstalling bash completions (optional):poetrycompletionsbash>>~/.bash_completionStart virtual environment🔖Setting up the Poetry environment for PyCharmCreating a virtual environment:poetryenvusepython3.10Installing dependencies:poetryinstallLaunching the shell and activating the virtual environment (from the project folder):poetryshellChecking virtual environment activation:poetryenvlist:arrow_up: ContentsInstall pre-commit hooksIn order for pre-commit checks to be performed with each commit, you must:Install pre-commitInstall pre-commit hooksInstall pre-commitThe pre-commit module has already been added to the requirements and should be installed automatically with the virtual environment.You can check the presence of pre-commit with the command (with the virtual environment activated):pre-commit--version# >> pre-commit 2.21.0If this does not happen, then you need toinstall pre-commit according to the official instructions:install via brew package manager:brew install pre-commitinstallation via poetry:poetry add pre-commitpip install:pip install pre-commit:arrow_up: ContentsInstall hooksInstalling hooks:pre-commitinstall--allIn the future, when executing thegit commitcommand, the checks listed in the.pre-commit-config.yamlfile will be performed.If it is not clear which error is preventing the commit from being executed, you can run the hooks manually with the command:pre-commitrun--all-files:arrow_up: ContentsExample UsageTo use the decorators provided by decorators-cryptography, follow the examples below.fromdecorators_cryptographyimportencrypt,decrypt@encrypt(key="encryption_key")defsensitive_function(arg1,arg2):# Your function implementationpass@decrypt(key="decryption_key")defsensitive_function(arg1,arg2):# Your function implementationpass:arrow_up: Contents
Package: decoratorsutility
decoratorsutilityIntroductionThis Python package provides decorators to handle exceptions, measure execution time, and set timeouts.InstallationTo install decoratorsutility, simply use pip:pipinstalldecoratorsutilityUsage Exampleexception_decDecorator to handle exceptions by logging errors to a specified file path.@exception_dec('module_name','/path/to/logfile.log')deffunction_name(*args,**kwargs):try:# Function executionreturnfunc(*args,**kwargs)exceptExceptionaserr:# Logs the error to the specified file pathlog_error(module=exc_mod,file_path=exc_path,error=err)logging.error(err)repeat_on_errorDecorator to retry function execution a set number of times in case of exceptions.@repeat_on_error(max_try=3,error_log='log/logfile.log',show_error=True)deftest_dummy(arg1:int):returnarg1/0timeout_decoratorDecorator to set a timeout for a function.fromdecoratorsutility.decoratorsimporttimeout_decorator@timeout_decorator(timeout=5)defmy_function():time.sleep(6)# Simulate a long-running functionreturn"Success!"DocumentationThe Sphinx-generated documentation for PathUtils can be foundhere.ContributionFeel free to contribute by submitting issueshere.
Package: decore
A small pure-python package for utility decorators.fromdecoreimportlazy_property@lazy_propertydefparamless_big_calc():sub_res=[big_func(const)forconstinarray_of_constants]returnsum(sub_res)Contents1Installation2Decorators2.1lazy_property2.2threadsafe_generator3Contributing3.1Installing for development3.2Running the tests3.3Adding documentation4Credits1InstallationInstalldecorewith:pipinstalldecore2Decorators2.1lazy_propertyThelazy_propertydecorator is meant to decorate functions that compute some constant value or property that you only want to compute once. The first call to the decorated function will run it and save the value (in memory) before returning it; subsequent calls will get this value without trigerring the calculation.You can think about it like afunctools.lru_cache(maxsize=1)for functions with no parameters.fromdecoreimportlazy_property@lazy_propertydefparamless_big_calc():"""I take a lot of time!"""sub_res=[big_func(const)forconstinarray_of_constants]returnsum(sub_res)2.2threadsafe_generatorThethreadsafe_generatordecorator makes generators threadsafe. This means multiple threads can be given references to the decorated generator and it is guarenteed that each item in the stream will be yielded (i.e. returned) to only a single thread.fromdecoreimportthreadsafe_generator@threadsafe_generatordefuser_documents(day):"""I yield some MongoDB documents!"""client=get_mongodb_client(some_params)dt_obj=translate_day_to_dt(day)user_document_cursor=client.some_mongodb_query(dt_obj,SOME_CONST)whileTrue:yielduser_document_cursor.__next__()3ContributingPackage author and current maintainer is Shay Palachy (shay.palachy@gmail.com); You are more than welcome to approach him for help. Contributions are very welcomed.3.1Installing for developmentClone:gitclonegit@github.com:shaypal5/decore.gitInstall in development mode with test dependencies:cdpdpipepipinstall-e".[test]"3.2Running the testsTo run the tests, use:python-mpytest--cov=decore3.3Adding documentationThis project is documented using thenumpy docstring conventions, which were chosen as they are perhaps the most widely-spread conventions that are both supported by common tools such as Sphinx and result in human-readable docstrings (in my personal opinion, of course). When documenting code you add to this project, please followthese conventions.4CreditsCreated by Shay Palachy  (shay.palachy@gmail.com).
Package: de-core
core portion of de namespace packagethe portions (modules and sub-packages) of the Development Environment for Python are within
thedenamespace and are providing helper methods and classes for your Python projects.installationexecute the following command to use thede.coremodule in your Python project. it will installde.coreinto your
Python (virtual) environment:pipinstallde-coreto contribute to this portion, fork thede-corerepository at GitLab,
pull it to your machine and finally execute the following command in the root folder of this repository (de_core):pipinstall-e.[dev]the last command will install this module portion into your virtual environment, along with the tools you need to
develop and run tests or to extend the portion documentation. to contribute only to the unit tests, or the documentation
of this portion replace the setup extras keydevin the above command withtestsordocsrespectively.the repository of this portion is using thegit-flow workflowwith the branch namesdevelopandrelease. more
details on this workflow you findhereandhere.namespace portion documentationmore info on the features and usage of this portion is available atReadTheDocs.
Package: decorit
decoritThe documentation including examples can be foundhere.This is a package with handy ready-to-use decorators for daily scripting and
maintaining packages. Decorator requests are highly appreciated, simply open
an issue.If you want to learn how to write your own decorators I recommand to head over
to realpython and check outthis article.
In case you are looking for an wrapper to easily write decorators for your own,
you might checkoutpydecor.This project is in an alpha stage, hence it is neither stable nor ready for
production.CAUTION:
Starting from version 1.0.0 API-breaking changes will be made only in major
releases. Until then, it can be changed in every minor release
(seechangelog).FeaturesExisting decorators:copy_doc: copy docstring of existing functioncopy_doc_params: copy parameters of docstring of existing functiondeprecated: print deprecated warning on callalias: give multiple names to function, e.g. short and longlogging: logging call of functionstime: timeing execution of functionrun_once: run function only once at first callUsageInstallationpython3-mpipinstalldecoritUsageimportdecorit# start decorating your functionsBuilding Documentation:The doc is based onpdocand can be created by
simply runningbash create_doc.shfrom the docs folder. For dependencies see in the
CI action.Similar ProjectspydecorCredits:In alphabetical order:realpython
Package: decoroute
Decorator style and pattern-matching based url routing library. No framework!
Very compact. Core logic less 100 lines of code. WSGI compliant. No additional API required.Complete exampleimport decoroute

app = decoroute.App(prefix='')

# pure WSGI
@app.expose('/wsgi/<id:\d+>')
@decoroute.wsgi('wsgiorg.routing_args')
def wsgi_app(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/plain')])
    return environ['wsgiorg.routing_args']

# pass variables into **kw
def render_response(status = '200 OK', content_type = 'text/plain', add_headers = [], **context):
    return status, [('Content-Type', content_type)] + add_headers, context

@app.expose('/node', id = '1')
@app.expose('/node/<id:\d+>')
def node(env, id):
    return render_response(id = id)

@app.expose('/url_for')
def url_for(env):
    return render_response(url = app.url_for(node, id = 666))

@app.expose('/404')
def not_found(env):
    raise decoroute.NotFound()

@app.not_found
def not_found_handler(env):
    return render_response(status = '404 NF', **env)

@app.render
def render(env, (status, headers, context)):
    context['site_uri'] = '%s://%s' % (env['wsgi.url_scheme'], env['HTTP_HOST'])
    return status, headers, ['%s=%s\n' %(k, context[k]) for k in context.keys()] # fake templating

from wsgiref.simple_server import make_server

make_server('', 6666, app).serve_forever()TipsIf you place your views (Django term. in ror - controller) in another modules, organize code likewerkzeug.# utils.py

import decoroute
app = decoroute.App()# view.py and anoter

from utils import *

@app.render
def render(env, ...)
    # returns of your endpoints pass to render handler
    # in render use your prefered template engine and return triple
    # status, generator of response headers, generator of response body
    # ( generator / iterator / list - any )
    # if you use default render endpoints must be return triple

@app.not_found
    # no route enpoint
    # it also pass to render handler

@app.expose('/node', id = '1')
@app.expose('/node/<id:\d+>')
def node(env, id):
    # endpoint passed some variables
    # env is a wsgi environ
    # id = '1' default value of parameter
    #   all parameters must be <type 'str'>
    # <id:\d+> parameter pattern;
    #   \d+ specify regexp constraint of parameter (required)# manage.py - main module

from utils import app
import view # and all other

if __name__ == '__main__':
    # serve app hereLegaldecoroute distributed under terms ofGNU LGPL v.2.1.Copyright 2008 - presentVsevolod Balashov.LinksSource code ofdecoroute.
Arch LinuxPKGBUILD.
Package: decorouter
Decorouter is a WSGI routing apparatus that makes it easy to define routes
using decorator syntax.Example:from decorouter import Router

class MyApplication:
    router = Router()

    @router.add('/$')
    def index(self, environ, start_response):
        start_response('200 OK', [('Content-type', 'text/plain')])
        return ['Hello, world!']

    @router.add('/hello/([^/]+)$')
    def index(self, environ, start_response):
        args, kwargs = environ['wsgiorg.routing_args']
        (name,) = args
        start_response('200 OK', [('Content-type', 'text/plain')])
        return ['Hello, %s!' % (name,)]

    def __call__(self, environ, start_response):
        return self.router(environ, start_response)

if __name__ == '__main__':
    from wsgiref.simple_server import make_server
    make_server('', 8000, MyApplication()).serve_forever()
Package: decorpy
DecorpyA collection of python decorators including time measurement, type checking and debugging.InstallationInstall the package directly usingPipwithPypipip install decorpyOr usinggitgit clone https://github.com/alexZajac/decorpy.gitcd decorpypython setup.py installExamplesMeasure execution time of a functionLink to gistDebugging a function with its signature and return valueLink to gistRuntime type-checking on function parameters and returnLink to gist
Package: decorrelator
DecorrelatorAnalysing correlations between parameters whilst controlling for the
effects of others.(Fancy partial correlation)Installationcreate new environmentconda create-nNAME python=3.7activatesource activate NAMEinstall high-performance librariesconda install numpy mkl scipyinstall correlatorpip installgit+https://github.com/philastrophist/decorrelator.gitUsePlease seeexample.pyfor an example which uses nearly all
functionalityThere are two objects of interest: *decorrelator.LinearRelation*decorrelator.CorrelationModelYou may use them together as demonstrated inexample.pyor
indivdually as shown in their home modules underif __name__ == "__main__"