module documentation

Routines to help with the creation, loading and introspection of modules, classes, hierarchies, attributes, functions, and methods.
Variable ​None​Type Undocumented
Class ​_hash​_limit​_string A string subclass that can only be hashed on a maximum amount of unique values.
Class ​_symbol No class docstring; 1/4 method documented
Class classproperty A decorator that behaves like @property except that operates on classes rather than instances.
Class ​Ensure​KWArg​Type Apply translation of functions to accept **kw arguments if they don't already.
Class ​Has​Memoized A class that maintains the names of memoized elements in a collection for easy cache clearing, generative, etc.
Class hybridmethod Decorate a function as cls- or instance- level.
Class hybridproperty Undocumented
Class memoized​_property A read-only @property that is only evaluated once.
Class ​Memoized​Slots Apply memoized items to an object using a __getattr__ scheme.
Class ​Plugin​Loader Undocumented
Class portable​_instancemethod Turn an instancemethod into a (parent, name) pair to produce a serializable callable.
Class safe​_reraise Reraise an exception after invoking some handler code.
Class symbol A constant symbol.
Function ​_dedent​_docstring Undocumented
Function ​_exec​_code​_in​_env Undocumented
Function ​_inspect​_func​_args Undocumented
Function ​_unique​_symbols Undocumented
Function ​_update​_argspec​_defaults​_into​_env given a FullArgSpec, convert defaults to be symbol names in an env.
Function ​_warnings​_warn Undocumented
Function add​_parameter​_text Undocumented
Function as​_interface Ensure basic interface compliance for an instance or dict of callables.
Function asbool Undocumented
Function asint Coerce to integer.
Function assert​_arg​_type Undocumented
Function attrsetter Undocumented
Function bool​_or​_str Return a callable that will evaluate a string as boolean, or one of a set of "alternate" string values.
Function chop​_traceback Chop extraneous lines off beginning and end of a traceback.
Function class​_hierarchy Return an unordered sequence of all classes related to cls.
Function clsname​_as​_plain​_name Undocumented
Function coerce​_kw​_type If 'key' is present in dict 'kw', coerce its value to type 'type_' if necessary. If 'flexi_bool' is True, the string '0' is considered false when coercing to boolean.
Function constructor​_copy Instantiate cls using the __dict__ of obj as constructor arguments.
Function constructor​_key Produce a tuple structure that is cacheable using the __dict__ of obj to retrieve values
Function counter Return a threadsafe counter function.
Function create​_proxy​_methods A class decorator that will copy attributes to a proxy class.
Function decode​_slice decode a slice object as sent to __getitem__.
Function decorator A signature-matching decorator factory.
Function dictlike​_iteritems Return a (key, value) iterator for almost any dict-like object.
Function duck​_type​_collection Given an instance or class, guess if it is or is acting as one of the basic collection types: list, set and dict. If the __emulates__ property is present, return that preferentially.
Function ellipses​_string Undocumented
Function format​_argspec​_init format_argspec_plus with considerations for typical __init__ methods
Function format​_argspec​_plus Returns a dictionary of formatted, introspected function arguments.
Function generic​_repr Produce a __repr__() based on direct association of the __init__() specification vs. same-named attributes present.
Function get​_callable​_argspec Return the argument signature for any callable.
Function get​_cls​_kwargs Return the full set of inherited kwargs for the given cls.
Function get​_func​_kwargs Return the set of legal kwargs for the given func.
Function getargspec​_init inspect.getargspec with considerations for typical __init__ methods
Function has​_compiled​_ext Undocumented
Function inject​_docstring​_text Undocumented
Function inject​_param​_text Undocumented
Function iterate​_attributes iterate all the keys and attributes associated with a class, without using getattr().
Function map​_bits Call the given function given each nonzero bit from n.
Function md5​_hex Undocumented
Function memoized​_instancemethod Decorate a method memoize its return value.
Function method​_is​_overridden Return True if the two class methods don't match.
Function methods​_equivalent Return True if the two methods are the same implementation.
Function monkeypatch​_proxied​_specials Automates delegation of __specials__ for a proxying type.
Function only​_once Decorate the given function to be a no-op after it is called exactly once.
Function public​_factory Produce a wrapping function for the given cls or classmethod.
Function quoted​_token​_parser Parse a dotted identifier with accommodation for quoted names.
Function repr​_tuple​_names Trims a list of strings from the middle and return a string of up to four elements. Strings greater than 11 characters will be truncated
Function set​_creation​_order Assign a '_creation_order' sequence to the given instance.
Function string​_or​_unprintable Undocumented
Function unbound​_method​_to​_callable Adjust the incoming callable such that a 'self' argument is not required.
Function walk​_subclasses Undocumented
Function warn Issue a warning.
Function warn​_exception executes the given function, catches all exceptions and converts to a warning.
Function warn​_limited Issue a warning with a parameterized string, limiting the number of registrations.
Function wrap​_callable Augment functools.update_wrapper() to work with objects with a __call__() method.
Constant ​_SQLA​_RE Undocumented
Constant ​_UNITTEST​_RE Undocumented
Variable ​_creation​_order Undocumented
Variable ​_param​_reg Undocumented
NoneType =

Undocumented

def _dedent_docstring(text):

Undocumented

def _exec_code_in_env(code, env, fn_name):

Undocumented

def _inspect_func_args(fn):

Undocumented

def _unique_symbols(used, *bases):

Undocumented

def _update_argspec_defaults_into_env(spec, env):
given a FullArgSpec, convert defaults to be symbol names in an env.
def _warnings_warn(message, category=None, stacklevel=2):

Undocumented

def add_parameter_text(params, text):

Undocumented

def as_interface(obj, cls=None, methods=None, required=None):

Ensure basic interface compliance for an instance or dict of callables.

Checks that obj implements public methods of cls or has members listed in methods. If required is not supplied, implementing at least one interface method is sufficient. Methods present on obj that are not in the interface are ignored.

If obj is a dict and dict does not meet the interface requirements, the keys of the dictionary are inspected. Keys present in obj that are not in the interface will raise TypeErrors.

Raises TypeError if obj does not meet the interface criteria.

In all passing cases, an object with callable members is returned. In the simple case, obj is returned as-is; if dict processing kicks in then an anonymous class is returned.

obj
A type, instance, or dictionary of callables.
cls
Optional, a type. All public methods of cls are considered the interface. An obj instance of cls will always pass, ignoring required..
methods
Optional, a sequence of method names to consider as the interface.
required
Optional, a sequence of mandatory implementations. If omitted, an obj that provides at least one interface method is considered sufficient. As a convenience, required may be a type, in which case all public methods of the type are required.
def asbool(obj):

Undocumented

def asint(value):
Coerce to integer.
def assert_arg_type(arg, argtype, name):

Undocumented

def attrsetter(attrname):

Undocumented

def bool_or_str(*text):
Return a callable that will evaluate a string as boolean, or one of a set of "alternate" string values.
def chop_traceback(tb, exclude_prefix=_UNITTEST_RE, exclude_suffix=_SQLA_RE):
Chop extraneous lines off beginning and end of a traceback.
Parameters
tba list of traceback lines as returned by traceback.format_stack()
exclude​_prefixa regular expression object matching lines to skip at beginning of tb
exclude​_suffixa regular expression object matching lines to skip at end of tb
def class_hierarchy(cls):

Return an unordered sequence of all classes related to cls.

Traverses diamond hierarchies.

Fibs slightly: subclasses of builtin types are not returned. Thus class_hierarchy(class A(object)) returns (A, object), not A plus every class systemwide that derives from object.

Old-style classes are discarded and hierarchies rooted on them will not be descended.

def clsname_as_plain_name(cls):

Undocumented

def coerce_kw_type(kw, key, type_, flexi_bool=True, dest=None):
If 'key' is present in dict 'kw', coerce its value to type 'type_' if necessary. If 'flexi_bool' is True, the string '0' is considered false when coercing to boolean.
def constructor_copy(obj, cls, *args, **kw):

Instantiate cls using the __dict__ of obj as constructor arguments.

Uses inspect to match the named arguments of cls.

def constructor_key(obj, cls):
Produce a tuple structure that is cacheable using the __dict__ of obj to retrieve values
def counter():
Return a threadsafe counter function.
def create_proxy_methods(target_cls, target_cls_sphinx_name, proxy_cls_sphinx_name, classmethods=(), methods=(), attributes=()):

A class decorator that will copy attributes to a proxy class.

The class to be instrumented must define a single accessor "_proxied".

def decode_slice(slc):

decode a slice object as sent to __getitem__.

takes into account the 2.5 __index__() method, basically.

def decorator(target):
A signature-matching decorator factory.
def dictlike_iteritems(dictlike):
Return a (key, value) iterator for almost any dict-like object.
def duck_type_collection(specimen, default=None):
Given an instance or class, guess if it is or is acting as one of the basic collection types: list, set and dict. If the __emulates__ property is present, return that preferentially.
def ellipses_string(value, len_=25):

Undocumented

def format_argspec_init(method, grouped=True):

format_argspec_plus with considerations for typical __init__ methods

Wraps format_argspec_plus with error handling strategies for typical __init__ cases:

object.__init__ -> (self)
other unreflectable (usually C) -> (self, *args, **kwargs)
def format_argspec_plus(fn, grouped=True):

Returns a dictionary of formatted, introspected function arguments.

A enhanced variant of inspect.formatargspec to support code generation.

fn
An inspectable callable or tuple of inspect getargspec() results.
grouped
Defaults to True; include (parens, around, argument) lists

Returns:

args
Full inspect.formatargspec for fn
self_arg
The name of the first positional argument, varargs[0], or None if the function defines no positional arguments.
apply_pos
args, re-written in calling rather than receiving syntax. Arguments are passed positionally.
apply_kw
Like apply_pos, except keyword-ish args are passed as keywords.
apply_pos_proxied
Like apply_pos but omits the self/cls argument

Example:

>>> format_argspec_plus(lambda self, a, b, c=3, **d: 123)
{'args': '(self, a, b, c=3, **d)',
 'self_arg': 'self',
 'apply_kw': '(self, a, b, c=c, **d)',
 'apply_pos': '(self, a, b, c, **d)'}
def generic_repr(obj, additional_kw=(), to_inspect=None, omit_kwarg=()):
Produce a __repr__() based on direct association of the __init__() specification vs. same-named attributes present.
def get_callable_argspec(fn, no_self=False, _is_init=False):

Return the argument signature for any callable.

All pure-Python callables are accepted, including functions, methods, classes, objects with __call__; builtins and other edge cases like functools.partial() objects raise a TypeError.

def get_cls_kwargs(cls, _set=None):

Return the full set of inherited kwargs for the given cls.

Probes a class's __init__ method, collecting all named arguments. If the __init__ defines a **kwargs catch-all, then the constructor is presumed to pass along unrecognized keywords to its base classes, and the collection process is repeated recursively on each of the bases.

Uses a subset of inspect.getfullargspec() to cut down on method overhead, as this is used within the Core typing system to create copies of type objects which is a performance-sensitive operation.

No anonymous tuple arguments please !

def get_func_kwargs(func):

Return the set of legal kwargs for the given func.

Uses getargspec so is safe to call for methods, functions, etc.

def getargspec_init(method):

inspect.getargspec with considerations for typical __init__ methods

Wraps inspect.getargspec with error handling for typical __init__ cases:

object.__init__ -> (self)
other unreflectable (usually C) -> (self, *args, **kwargs)
def has_compiled_ext():

Undocumented

def inject_docstring_text(doctext, injecttext, pos):

Undocumented

def inject_param_text(doctext, inject_params):

Undocumented

def iterate_attributes(cls):

iterate all the keys and attributes associated with a class, without using getattr().

Does not use getattr() so that class-sensitive descriptors (i.e. property.__get__()) are not called.

def map_bits(fn, n):
Call the given function given each nonzero bit from n.
def md5_hex(x):

Undocumented

def memoized_instancemethod(fn):

Decorate a method memoize its return value.

Best applied to no-arg methods: memoization is not sensitive to argument values, and will always return the same value even when called with different arguments.

def method_is_overridden(instance_or_cls, against_method):
Return True if the two class methods don't match.
def methods_equivalent(meth1, meth2):
Return True if the two methods are the same implementation.
def monkeypatch_proxied_specials(into_cls, from_cls, skip=None, only=None, name='self.proxy', from_instance=None):
Automates delegation of __specials__ for a proxying type.
def only_once(fn, retry_on_exception):
Decorate the given function to be a no-op after it is called exactly once.
def public_factory(target, location, class_location=None):

Produce a wrapping function for the given cls or classmethod.

Rationale here is so that the __init__ method of the class can serve as documentation for the function.

def quoted_token_parser(value):

Parse a dotted identifier with accommodation for quoted names.

Includes support for SQL-style double quotes as a literal character.

E.g.:

>>> quoted_token_parser("name")
["name"]
>>> quoted_token_parser("schema.name")
["schema", "name"]
>>> quoted_token_parser('"Schema"."Name"')
['Schema', 'Name']
>>> quoted_token_parser('"Schema"."Name""Foo"')
['Schema', 'Name""Foo']
def repr_tuple_names(names):
Trims a list of strings from the middle and return a string of up to four elements. Strings greater than 11 characters will be truncated
def set_creation_order(instance):

Assign a '_creation_order' sequence to the given instance.

This allows multiple instances to be sorted in order of creation (typically within a single thread; the counter is not particularly threadsafe).

def string_or_unprintable(element):

Undocumented

def unbound_method_to_callable(func_or_cls):
Adjust the incoming callable such that a 'self' argument is not required.
def walk_subclasses(cls):

Undocumented

def warn(msg, code=None):

Issue a warning.

If msg is a string, .exc.SAWarning is used as the category.

def warn_exception(func, *args, **kwargs):
executes the given function, catches all exceptions and converts to a warning.
def warn_limited(msg, args):
Issue a warning with a parameterized string, limiting the number of registrations.
def wrap_callable(wrapper, fn):
Augment functools.update_wrapper() to work with objects with a __call__() method.
Parameters
wrapperUndocumented
fnobject with __call__ method
_SQLA_RE =

Undocumented

Value
re.compile(r'sqlalchemy/([a-z_]+/){,2}[a-z_]+\.py')
_UNITTEST_RE =

Undocumented

Value
re.compile(r'unit(?:2|test2?/)')
_creation_order: int =

Undocumented

_param_reg =

Undocumented