Saravanan666/pypi-org huggingface dataset:
Package: contextdecorator
If you’re a library or framework creator then it is nice to be able to create
APIs that can be usedeitheras decorators or context managers.The contextdecorator module is a backport of new features added to thecontextlib modulein
Python 3.2. contextdecorator works with Python 2.4+ including Python 3.Context managers inheriting fromContextDecoratorhave to implement__enter__and__exit__as normal.__exit__retains its optional exception handling even when used as a decorator.Example:from contextdecorator import ContextDecorator

class mycontext(ContextDecorator):
   def __enter__(self):
      print 'Starting'
      return self

   def __exit__(self, *exc):
      print 'Finishing'
      return False

>>> @mycontext()
... def function():
...    print 'The bit in the middle'
...
>>> function()
Starting
The bit in the middle
Finishing

>>> with mycontext():
...    print 'The bit in the middle'
...
Starting
The bit in the middle
FinishingExisting context managers that already have a base class can be extended by
usingContextDecoratoras a mixin class:from contextdecorator import ContextDecorator

class mycontext(ContextBaseClass, ContextDecorator):
   def __enter__(self):
      return self

   def __exit__(self, *exc):
      return Falsecontextdecorator also contains an implementation ofcontextlib.contextmanagerthat usesContextDecorator. The context managers it creates can be used as
decorators as well as in with statements.from contextdecorator import contextmanager

@contextmanager
def mycontext(*args):
   print 'Started'
   try:
      yield
   finally:
      print 'Finished!'

>>> @mycontext('some', 'args')
... def function():
...    print 'In the middle'
...
Started
In the middle
Finished!

>>> with mycontext('some', 'args'):
...    print 'In the middle'
...
Started
In the middle
Finished!Repository and issue tracker:contextdecorator on google codeThe project is available for download fromPyPIso it can be easily installed:pip install-Ucontextdecoratoreasy_install-UcontextdecoratorThe tests requireunittest2to run.
Package: contextfilter
contextfilterSmall, helper library for logging contextual information using contextvars in Python 3.7.InstallationUsing pip$ pip install contextfilterUsageimportloggingfromcontextvarsimportContextVarfromcontextfilterimportContextVarFilter,ConstContextFilterrequest_id:ContextVar[int]=ContextVar('request_id')logger=logging.getLogger("test")cf=ContextFilter(request_id=request_id)request_id.set(3)logger.addFilter(cf)logger.info("test")# Log record will contain the attribute request_id with value 3cf=ConstContextFilter(some_const=1)logger.addFilter(cf)logger.info("test")# Log record will contain the attribute some_const with value 1.ContributingTo work on thecontextfiltercodebase, you'll want to fork the project and clone it locally and install the required dependencies viapoetry:$gitclonegit@github.com:{USER}/contextfilter.git
$makeinstallTo run tests and linters use command below:$makelint&&maketestIf you want to run only tests or linters you can explicitly specify which test environment you want to run, e.g.:$makelint-blackLicensecontextfilteris licensed under the MIT license. See the license file for details.Latest changes0.3.0 (2020-8-14)RenamedContextFiltertoContextVarFilter- Revamped the API - It now accepts ContextVars created by caller. Suggestion for design by @bentheiiiAddedConstContextFilterwhich adds constant attributes to the log record.Fixed #5
Package: contextfree
CFDG-inspired cairo-based pythonic generative art toolHere is an example of simple code producing stochastic fractal tree:fromcontextfree.contextfreeimport*@check_limitsdefbranch():line(0,1)withtranslate(0,0.9):withscale(0.7+rnd(0.15)):withcolor(alpha=0.95):withrotate(-0.3+rnd(0.3)):branch()withrotate(0.3+rnd(0.3)):branch()init(canvas_size=(300,300),background_color="#FFFFFF")withscale(3):branch()display_ipython()Here is the output:Check examples folder for more fun stuff.How do I get set up?pip3 install contextfreefor latest stable releasepip3 installgit+https://github.com/undertherain/pycontextfree.gitfor recent development versionPython 3.6 or later is required
Package: contextif
contextif: run the function only in a specific contextSometimes we may need to run a function only if it happens in a strictly defined context. In this case, we can use this mini library.Install it:pipinstallcontextifAnd use:fromcontextifimportstatewithstate:state(print,'hello,','world!')# It will be printed.state(print,"it's me, Mario!")# It won't.Usingstateas a function, you can pass another function and arguments to it there. It will be called only if it happens in a context created also usingstate. The function will not be called out of context.For convenience, after the first import ofstate, this variable becomes builtin and you can access it in other modules of your program without importing.
Package: contextily
contextily: context geo tiles in Pythoncontextilyis a small Python 3 (3.8 and above) package to retrieve tile maps from the
internet. It can add those tiles as basemap to matplotlib figures or write tile
maps to disk into geospatial raster files. Bounding boxes can be passed in both
WGS84 (EPSG:4326) and Spheric Mercator (EPSG:3857). See the notebookcontextily_guide.ipynbfor usage.The current tile providers that are available in contextily are the providers
defined in thexyzservicespackage. This includes some popular tile maps, such as:The standardOpenStreetMapmap tilesToner, Terrain and Watercolor map tiles byStamen DesignDependenciesmercantilenumpymatplotlibpillowrasteriorequestsgeopyjoblibxyzservicesInstallationPython 3 only(3.8 and above)Latest released version, using pip:pip3installcontextilyor conda:condainstallcontextilyContributorscontextilyis developed by a community of enthusiastic volunteers. You can see a full listhere.If you would like to contribute to the project, have a look at the list ofopen issues, particularly those labeled asgood first contributions.LicenseBSD compatible. SeeLICENSE.txt
Package: context-io-2
Context.IO API v2.0 Python Library==================================This is the python client library for v2.0 of the Context.IO API!##DependenciesRAUTH - If you do not have that, snag it with```$ pip install rauth```or```$ easy_install rauth```, or “Use the [Source](https://github.com/litl/rauth), Luke”REQUESTS - rauth is built on top of the requests module```$ pip install requests```or```$ easy_install requests```or [Source](https://github.com/kennethreitz/requests)##InstallationCheck out / download the module from git, change directory to the folder with setup.py and run:python setup.py installYou'll probably want to toss a sudo before that, depending on your OS. That's it though!##UsageYou first need to instantiate the main ContextIO object with your API credentials:import contextio as cCONSUMER_KEY = 'YOUR_API_KEY'CONSUMER_SECRET = 'YOUR_API_SECRET'context_io = c.ContextIO(consumer_key=CONSUMER_KEY,consumer_secret=CONSUMER_SECRET)The ContextIO class can optionally accept a debug keyword parameter that prints or logs more info about the request and response.The module is fully docstringed out, so feel free to jump into the python interpreter and help(foo) on stuff. Explore the resource classes and methods!Here's how you can query the API for an account:accounts = context_io.get_accounts(email='johndoe@gmail.com')# since we return a list, let's be sure we have a resultif accounts:account = accounts[0]The Account class has methods to represent all the kinds of requests you can make under that resource.If you store account ids, message ids, file ids, or anything else like that on your server, you can instantiate these objects without touching the API, for increased speed. Here's an example of how you do that.params = {'id': 'ACCOUNT_ID_HERE'}account = c.Account(context_io, params)That'll just be an empty object, but you need to pass in the "id" since that's used to form the URL for API endpoints for the account resource. If you want to query the API and populate that account object, you can simply do a:account.get()You can use this same technique to populate sub-resource objects too.params = {'message_id': 'MESSAGE_ID_HERE'}message = c.Message(account, params)# populate the message object with data from the APImessage.get()Notice how the Message class needs an Account object as a parent? That's because the library uses an object's ancestors to build the URL.If you have any questions, don't hesitate to contact tony@context.io (that's me!). I'd love to assist you with any issues you encounter and learn how you'll use Context.IO!
Package: contextlib2
contextlib2 is a backport of thestandard library’s contextlib
moduleto
earlier Python versions.It also sometimes serves as a real world proving ground for possible future
enhancements to the standard library version.LicensingAs a backport of Python standard library software, the implementation, test
suite and other supporting files for this project are distributed under the
Python Software License used for the CPython reference implementation.The one exception is the included type hints file, which comes from thetypeshedproject, and is hence distributed under the Apache License 2.0.Developmentcontextlib2 has no runtime dependencies, but requiressetuptoolsandwheelat build time to generate universal wheel archives.Local testing is a matter of running:python3 -m unittest discover -t . -s testYou can test against multiple versions of Python withtox:pip install tox
toxVersions currently tested in both tox and GitHub Actions are:CPython 3.6CPython 3.7CPython 3.8CPython 3.9CPython 3.10PyPy3Updating to a new stdlib reference versionAs of Python 3.10, 4 files needed to be copied from the CPython reference
implementation to contextlib2:Doc/contextlib.rst->docs/contextlib2.rstLib/contextlib.py->contextlib2/__init__.pyLib/test/test_contextlib.py->test/test_contextlib.pyLib/test/test_contextlib_async.py->test/test_contextlib_async.pyThe corresponding version ofcontextlib2/__init__.pyialso needs to be
retrieved from thetypeshedproject:wget https://raw.githubusercontent.com/python/typeshed/master/stdlib/contextlib.pyiFor the 3.10 sync, the only changes needed to the test files were to import fromcontextlib2rather thancontextlib. The test directory is laid out so
that the test suite’s imports fromtest.supportwork the same way they do in
the main CPython test suite.The following patch files are saved in thedevdirectory:changes made tocontextlib2/__init__.pyto get it to run on the older
versions (and to add back in the deprecated APIs that never graduated to
the standard library version)changes made tocontextlib2/__init__.pyito make the Python version
guards unconditional (since thecontextlib2API is the same on all
supported versions)changes made todocs/contextlib2.rstto usecontextlib2version
numbers in the version added/changed notes and to integrate the module
documentation with the rest of the project documentation
Package: contextlib-chdir
contextlib-chdirBackport ofcontextlib.chdirstdlib class added in Python3.11.Installpip install contextlib-chdirUsageimportosimporttempfilefromcontextlib_chdirimportchdiraschdir_ctxwithchdir_ctx(tempfile.gettempdir()):print(os.getcwd())# /tmpNoteYou'll probably want to migrate tocontextlib2whenthis change is included.
Package: contextlib-ext
contextlib-ext - extensions for contextlibcontextlib-extis a complimentary library forcontextlib, it provides a following helpers:suppressas a decoratorsuppresscan be used as a decoratorfromcontextlib_extimportsuppress@suppress(Exception)defphony_func():raiseValueErrorphony_func()print("No exceptions")@asynccontextmanagercreates decorator@asynccontextmanagercreates context manager that can be used as a decorator (contextlib.contextmanageralready supports it)fromcontextlib_extimportasynccontextmanager@asynccontextmanagerasyncdefmymanager():yield# The same as contextlib.asynccontextmanagerasyncwithmymanager():pass# This also works@mymanagerasyncdefmyfunc():passasync_suppressasync_suppress- the same assuppress, but asyncfromcontextlib_extimportasync_suppresstry:asyncwithasync_suppress(Exception):raiseValueErrorexceptException:assertFalse# never happenselse:print("No exceptions")# Works as decorator too@async_suppress(Exception)asyncdefphony_func():raiseValueErrorphony_func()print("No exceptions")
Package: contextlocal
Context LocalsExtract the context local functionality fromWerkzeug.This is generally useful for a variety of contexts, where you may not want to include a full WSGI library.UsagePlease see the documenation athttps://werkzeug.palletsprojects.com/en/latest/local/LicenseThis is derived from Werkzeug with minimal modifications, and is under the same BSD 3-Clause license.Please see theLICENSEfile for details.
Package: context_logging
context_loggingDescriptionTool for easy logging with current context information.fromcontext_loggingimportcurrent_contextlogging.info('before context')# 2019-07-25 19:49:43 INFO before contextwithContext('my_context'):current_context['var']=1logging.info('in context')# 2019-07-25 19:49:43 INFO in context {'var': 1}# 2019-07-25 19:49:43 INFO 'my_context: executed in 00:00:01 {'var': 1}'logging.info('after context')# 2019-07-25 19:49:43 INFO after contextInstallationpip install context_loggingUsageSetup logging with contextimportloggingfromcontext_loggingimportcurrent_context,setup_log_recordlogging.basicConfig(format='%(asctime)s%(levelname)s%(name)s%(message)s%(context)s',level=logging.INFO,)setup_log_record()current_context['var']=1logging.info('message')# 2019-07-25 19:49:43,892 INFO root message {'var': 1}As contextmanagerfromcontext_loggingimportContext,current_contextwithContext(var=1):assertcurrent_context['var']==1assert'var'notincurrent_contextAny nesting of contexts is allowedwithContext(var=1):assertcurrent_context=={'var':1}withContext(val=2,var=2):assertcurrent_context=={'val':2,'var':2}assertcurrent_context=={'var':1}assert'var'notincurrent_contextAs decorator@Context(var=1)deff():assertcurrent_context['var']==1f()assert'var'notincurrent_contextWith start/finish [DEPRECATED]ctx=Context(var=1)assert'var'notincurrent_contextctx.start()assertcurrent_context['var']==1ctx.finish()assert'var'notincurrent_contextAdd/remove values from current_contextwithContext():assert'var'notincurrent_contextcurrent_context['var']=1assertcurrent_context['var']==1Explicit context name (else will be used path to the python module)withContext('my_context'):passExecution time logged on exit from context (it can be disabled withlog_execution_time=Falseargument)withContext('my_context'):time.sleep(1)# INFO 'my_context: executed in 00:00:01',Default value for log_execution_time param can be changed with envexport CONTEXT_LOGGING_LOG_EXECUTION_TIME_DEFAULT=0Exceptions from context are populated with current_context (it can be disabled withfill_exception_context=Falseargument)try:withContext(var=1):raiseException(1)exceptExceptionasexc:assertexc.args=(1,{'var':1})Default value for fill_exception_context param can be changed with envexport CONTEXT_LOGGING_FILL_EXEPTIONS_DEFAULT=0We can set data to root context that never will be closedfromcontext_loggingimportroot_contextroot_context['env']='test'If you want to pass context to other threads useContextVarExecutorfromcontext_loggingimportContextVarExecutorwithContextVarExecutor()asexecutor:executor.submit(...)# ORloop.set_default_executor(ContextVarExecutor())# for asyncio loopFor developersCreate venv and install depsmake initInstall git precommit hookmake precommit_hookRun linters, autoformat, tests etc.make pretty lint testBump new versionmake bump_major
make bump_minor
make bump_patch
Package: context-loop
Info:Context loop.Author:Paweł Zadrożny @pawelzny <pawel.zny@gmail.com>FeaturesWork with sync and async frameworksSchedule tasks to existing loop or create new oneNo need to understand how async worksNo callbacks requiredRun async tasks whenever and wherever you wantInstallationpipinstallcontext-loopPackage:https://pypi.org/project/context-loop/DocumentationRead full documentation athttp://context-loop.readthedocs.io/en/stable/Quick Example>>>asyncdefcoro():...returnawaitsomething_from_future()...>>>importcl.Loop>>>withcl.Loop(coro(),coro(),coro())asloop:...result=loop.run_until_complete()...>>>result['success','success','success']
Package: contextmanaged-assign
ContextManaged AssignThis Python project provides a context manager for temporarily assigning a value to a variable or attribute. The original value is restored when the context is exited.Usagefromcontextmanaged_assignimportassignl=[1,2,3]assertl[0]==1withassign("l[0]",2):assertl[0]==2assertl[0]==1Please note thatassigncannot modify local variables themselves. For example, the following code will not work:x=1withassign("x",2):assertx==2# AssertionError: 1 != 2assertx==1InstallationSimply install the package usingpip:pipinstallcontextmanaged-assignThen import theassignfunction from thecontextmanaged-assignmodule.LicenseMIT
Package: contextmanaged-objects
Context-Managed Objects in PythonThis project provides a way to manage objects in a global or thread-wise context-aware manner in Python. It includes a class HasContextManagedFocus and a decorator make_current. These tools can be particularly useful in scenarios where you need to manage context-specific objects like user credentials or other parameters that are frequently passed around in a backend application.Getting StartedThis project is available on PyPI. You can install it using pip:pipinstallcontextmanaged-objectsUsageConsider a scenario where you're building a web application and you need to keep track of the current user's credentials. Instead of passing the user credentials as arguments to every function, you can use HasContextManagedFocus and make_current to manage the current user context.fromcontextmanaged_objectsimportHasContextManagedFocus,make_currentclassUser(HasContextManagedFocus):def__init__(self,username,password):self.username=usernameself.password=password@make_current()defstart_doing_something(self):# do something with the current usercall_first_library_function()...fiftieth_library_function():# do something with the current usercurrent_user=User.get_current()# we didn't have to pass current_user as an argument along the entire 1st-49th library function chainuser1=User('user1','password1')user2=User('user2','password2')In this example, User is a subclass ofHasContextManagedFocus. Thedo_somethingmethod is decorated withmake_current, so wheneverdo_somethingis invoked,user1oruser2(whichever is the current instance) is placed on top of the context stack. This allows you to easily manage the current user context without having to pass user credentials around.API ReferenceHasContextManagedFocusThis class allows objects to be context-managed. It maintains a context stack where instances can be placed on top of the stack and retrieved. The as_current method is a context manager that puts the instance on top of its context stack.make_currentThis function is a decorator for instance methods. It automatically puts the instance on top of its context stack during invocation and removes it after invocation is over.MultithreadingCall the.enable_threaded_context()or.disable_threaded_context()to enable or disable thread-specific context management. By default, threaded context management is disabled.fromcontextmanaged_objectsimportHasContextManagedFocus,make_currentHasContextManagedFocus.enable_threaded_context()...ContributingPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.We use pytest for testing. To run the tests, run the following command from the root directory of the project:poetryrunpytestPlease make sure to update tests as appropriate.LicenseWe use theMITlicense. If you make contributions to this project, you agree to license your contributions under the MIT license and you may include your name in the list of authors.
Package: context-managed-singleton
Context Managed Singleton
This is a Python utility module that provides a base class for creating a singleton that can be used in a context manager. The purpose of the context manager is to allow for easy management of the state of the singleton in a multithreaded environment where the singleton needs to be accessed and modified by multiple threads simultaneously.UsageBasic Usagefromcontext_managed_singletonimportContextManagedSingleton# Create an instance of ContextManagedSingletonctx=ContextManagedSingleton()# Use the instance in a with blockwithctx:# Do something with the singleton...# The instance is automatically removed from the stack when the with block is exitedAdvanced UsageThe ContextManagedSingleton class can be subclassed to create a custom singleton with additional functionality. The class can also be wrapped around an existing class using the wrap static method.fromcontext_managed_singletonimportContextManagedSingleton# Subclass the ContextManagedSingleton classclassMyClass(ContextManagedSingleton):...# (alternatively, wrap with ContextManagedSingleton.wrap decorator)# @ContextManagedSingleton.wrap# class MyClass:deffoo():# don't bother forwarding the instance to foo()# just get the current instance from the .current() class methodmy_instance=MyClass.current()...withMySingleton():# lots of code and deeply buried calls to foo()...Nested ContextsThe ContextManagedSingleton class can be used in nested contexts.fromcontext_managed_singletonimportContextManagedSingleton# Create an instance of ContextManagedSingletonctx=ContextManagedSingleton()# Use the instance in a with blockwithctx:# Do something with the singleton...# Create a nested contextwithctx:# Do something with the nested singleton...# The instances are automatically removed from the stack when the with blocks are exitedRecursive Attribute AccessThe ContextManagedSingleton class supports recursive attribute access. When an attribute is not found on the current instance, the class will look for the attribute on the previous instance in the stack.fromcontext_managed_singletonimportContextManagedSingleton# create and enter a contextwithContextManagedSingleton({"a":1,"b":2}):withContextManagedSingleton({"a":4},getattr_recursive=True):print(ContextManagedSingleton.current().a)# prints 4print(ContextManagedSingleton.current().b)# prints 2print(ContextManagedSingleton.current().a)# prints 1print(ContextManagedSingleton.current().b)# prints 2# The instances are automatically removed from the stack when the with blocks are exitedTestsThe tests for the ContextManagedSingleton class can be found in the tests directory. To run the tests, run the following command:python-munittestdiscovertestsLicenseThis project is licensed under the MIT License. See the LICENSE file for more information.