guv.patcher - monkey-patching the standard library

guv.patcher.monkey_patch(**modules)[source]

Globally patch/configure system modules to to be greenlet-friendly

If no keyword arguments are specified, all possible modules are patched. If keyword arguments are specified, the specified modules (and their dependencies) will be patched.

It’s safe to call monkey_patch multiple times.

Example:

monkey_patch(time=True, socket=True, select=True)
Parameters:
  • time (bool) – time module: patches sleep()
  • os (bool) – os module: patches open(), read(), write(), wait(), waitpid()
  • socket (bool) – socket module: patches socket, create_connection()
  • select (bool) – select module: patches select()
  • threading (bool) – threading module: patches local, Lock(), stack_size(), current_thread()
  • psycopg2 (bool) – psycopg2 module: register a wait callback to yield
  • cassandra (bool) – cassandra module: set connection class to GuvConnection
guv.patcher.original(modname)[source]

Return an unpatched version of a module

This is useful for guv itself.

Parameters:modname (str) – name of module
guv.patcher.is_monkey_patched(module)[source]

Check if the specified module is currently patched

Based entirely off the name of the module, so if you import a module some other way than with the import keyword (including import_patched), this might not be correct about that particular module

Parameters:module (module or str) – module to check (moduble object itself, or its name str)
Returns:True if the module is patched else False
Return type:bool
guv.patcher.inject(module_name, new_globals, *additional_modules)[source]

Inject greenified modules into an imported module

This method imports the module specified in module_name, arranging things so that the already-imported modules in additional_modules are used when module_name makes its imports.

new_globals is either None or a globals dictionary that gets populated with the contents of the module_name module. This is useful when creating a “green” version of some other module.

additional_modules should be a collection of two-element tuples, of the form (name: str,  module: str). If it’s not specified, a default selection of name/module pairs is used, which should cover all use cases but may be slower because there are inevitably redundant or unnecessary imports.

guv.patcher.import_patched(module_name, *additional_modules, **kw_additional_modules)[source]

Import patched version of module

Parameters:module_name (str) – name of module to import
guv.patcher.patch_function(func, *additional_modules)[source]

Decorator that returns a version of the function that patches some modules for the duration of the function call

This should only be used for functions that import network libraries within their function bodies that there is no way of getting around.