module documentation

Routines to help with the creation, loading and introspection of modules, classes, hierarchies, attributes, functions, and methods.

Class classproperty A decorator that behaves like @property except that operates on classes rather than instances.
Class EnsureKWArg Apply translation of functions to accept \**kw arguments if they don't already.
Class generic_fn_descriptor Descriptor which proxies a function when the attribute is not present in dict
Class HasMemoized A mixin 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 MemoizedSlots Apply memoized items to an object using a __getattr__ scheme.
Class PluginLoader Undocumented
Class portable_instancemethod Turn an instancemethod into a (parent, name) pair to produce a serializable callable.
Class rw_hybridproperty Undocumented
Class safe_reraise Reraise an exception after invoking some handler code.
Class symbol A constant symbol.
Class TypingOnly A mixin class that marks a class as 'typing only', meaning it has absolutely no methods, attributes, or runtime functionality whatsoever.
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 indicating attributes should refer 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_annotations Undocumented
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 parse_user_argument_for_enum Given a user parameter, parse the parameter into a chosen value from a list of choice objects, typically Enum values.
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 tag_method_for_warnings 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.
Variable NoneType Undocumented
Class _FastIntFlag An 'IntFlag' copycat that isn't slow when performing bitwise operations.
Class _hash_limit_string A string subclass that can only be hashed on a maximum amount of unique values.
Class _IntFlagMeta Undocumented
Class _memoized_property A read-only @property that is only evaluated once.
Class _non_memoized_property a plain descriptor that proxies a function.
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
Constant _SQLA_RE Undocumented
Constant _UNITTEST_RE Undocumented
Type Variable _E Undocumented
Type Variable _F Undocumented
Type Variable _Fn Undocumented
Type Variable _GFD Undocumented
Type Variable _HM Undocumented
Type Variable _HP Undocumented
Type Variable _MA Undocumented
Type Variable _MP Undocumented
Type Variable _PF Undocumented
Type Variable _T Undocumented
Type Variable _T_co Undocumented
Type Variable _TE Undocumented
Variable _creation_order Undocumented
Variable _not_sa_pattern Undocumented
Variable _param_reg Undocumented
Variable _warning_tags Undocumented
def add_parameter_text(params: Any, text: str) -> Callable[[_F], _F]: (source)

Undocumented

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

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: Any) -> bool: (source)

Undocumented

def asint(value: Any) -> Optional[int]: (source)

Coerce to integer.

def assert_arg_type(arg: Any, argtype: Union[Tuple[Type[Any], ...], Type[Any]], name: str) -> Any: (source)

Undocumented

def attrsetter(attrname): (source)

Undocumented

def bool_or_str(*text: str) -> Callable[[str], Union[str, bool]]: (source)

Return a callable that will evaluate a string as boolean, or one of a set of "alternate" string values.

def chop_traceback(tb: List[str], exclude_prefix: re.Pattern[str] = _UNITTEST_RE, exclude_suffix: re.Pattern[str] = _SQLA_RE) -> List[str]: (source)

Chop extraneous lines off beginning and end of a traceback. :param tb: a list of traceback lines as returned by ``traceback.format_stack()`` :param exclude_prefix: a regular expression object matching lines to skip at beginning of ``tb`` :param exclude_suffix: a regular expression object matching lines to skip at end of ``tb``

def class_hierarchy(cls): (source)

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.

def clsname_as_plain_name(cls: Type[Any]) -> str: (source)

Undocumented

def coerce_kw_type(kw: Dict[str, Any], key: str, type_: Type[Any], flexi_bool: bool = True, dest: Optional[Dict[str, Any]] = None): (source)

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: _T, cls: Type[_T], *args: Any, **kw: Any) -> _T: (source)

Instantiate cls using the __dict__ of obj as constructor arguments. Uses inspect to match the named arguments of ``cls``.

def constructor_key(obj: Any, cls: Type[Any]) -> Tuple[Any, ...]: (source)

Produce a tuple structure that is cacheable using the __dict__ of obj to retrieve values

def counter() -> Callable[[], int]: (source)

Return a threadsafe counter function.

def create_proxy_methods(target_cls: Type[Any], target_cls_sphinx_name: str, proxy_cls_sphinx_name: str, classmethods: Sequence[str] = (), methods: Sequence[str] = (), attributes: Sequence[str] = ()) -> Callable[[_T], _T]: (source)

A class decorator indicating attributes should refer to a proxy class. This decorator is now a "marker" that does nothing at runtime. Instead, it is consumed by the tools/generate_proxy_methods.py script to statically generate proxy methods and attributes that are fully recognized by typing tools such as mypy.

def decode_slice(slc: slice) -> Tuple[Any, ...]: (source)

decode a slice object as sent to __getitem__. takes into account the 2.5 __index__() method, basically.

def decorator(target: Callable[..., Any]) -> Callable[[_Fn], _Fn]: (source)

A signature-matching decorator factory.

def dictlike_iteritems(dictlike): (source)

Return a (key, value) iterator for almost any dict-like object.

def duck_type_collection(specimen: Any, default: Optional[Type[Any]] = None) -> Optional[Type[Any]]: (source)

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): (source)

Undocumented

def format_argspec_init(method, grouped=True): (source)

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: Union[Callable[..., Any], compat.FullArgSpec], grouped: bool = True) -> Dict[str, Optional[str]]: (source)

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) {'grouped_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: Any, additional_kw: Sequence[Tuple[str, Any]] = (), to_inspect: Optional[Union[object, List[object]]] = None, omit_kwarg: Sequence[str] = ()) -> str: (source)

Produce a __repr__() based on direct association of the __init__() specification vs. same-named attributes present.

def get_annotations(obj: Any) -> Mapping[str, Any]: (source)

Undocumented

def get_callable_argspec(fn: Callable[..., Any], no_self: bool = False, _is_init: bool = False) -> compat.FullArgSpec: (source)

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.

@overload
def get_cls_kwargs(cls: type, *, _set: Optional[Set[str]] = None, raiseerr: Literal[True] = ...) -> Set[str]:
@overload
def get_cls_kwargs(cls: type, *, _set: Optional[Set[str]] = None, raiseerr: bool = False) -> Optional[Set[str]]:
(source)

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: Callable[..., Any]) -> List[str]: (source)

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): (source)

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(raise_=False): (source)

Undocumented

def inject_docstring_text(given_doctext: Optional[str], injecttext: str, pos: int) -> str: (source)

Undocumented

def inject_param_text(doctext: str, inject_params: Dict[str, str]) -> str: (source)

Undocumented

def iterate_attributes(cls): (source)

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: Callable[[int], Any], n: int) -> Iterator[Any]: (source)

Call the given function given each nonzero bit from n.

def md5_hex(x: Any) -> str: (source)

Undocumented

def memoized_instancemethod(fn: _F) -> _F: (source)

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: Union[Type[Any], object], against_method: Callable[..., Any]) -> bool: (source)

Return True if the two class methods don't match.

def methods_equivalent(meth1, meth2): (source)

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): (source)

Automates delegation of __specials__ for a proxying type.

def only_once(fn: Callable[..., _T], retry_on_exception: bool) -> Callable[..., Optional[_T]]: (source)

Decorate the given function to be a no-op after it is called exactly once.

def parse_user_argument_for_enum(arg: Any, choices: Dict[_E, List[Any]], name: str, resolve_symbol_names: bool = False) -> Optional[_E]: (source)

Given a user parameter, parse the parameter into a chosen value from a list of choice objects, typically Enum values. The user argument can be a string name that matches the name of a symbol, or the symbol object itself, or any number of alternate choices such as True/False/ None etc. :param arg: the user argument. :param choices: dictionary of enum values to lists of possible entries for each. :param name: name of the argument. Used in an :class:`.ArgumentError` that is raised if the parameter doesn't match any available argument.

def quoted_token_parser(value): (source)

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: List[str]) -> Optional[str]: (source)

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: Any): (source)

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: Any) -> str: (source)

Undocumented

def tag_method_for_warnings(message: str, category: Type[Warning]) -> Callable[[_F], _F]: (source)

Undocumented

def unbound_method_to_callable(func_or_cls): (source)

Adjust the incoming callable such that a 'self' argument is not required.

def walk_subclasses(cls: Type[_T]) -> Iterator[Type[_T]]: (source)

Undocumented

def warn(msg: str, code: Optional[str] = None): (source)

Issue a warning. If msg is a string, :class:`.exc.SAWarning` is used as the category.

def warn_exception(func: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: (source)

executes the given function, catches all exceptions and converts to a warning.

def warn_limited(msg: str, args: Sequence[Any]): (source)

Issue a warning with a parameterized string, limiting the number of registrations.

def wrap_callable(wrapper, fn): (source)

Augment functools.update_wrapper() to work with objects with a ``__call__()`` method. :param fn: object with __call__ method

NoneType = (source)

Undocumented

def _dedent_docstring(text: str) -> str: (source)

Undocumented

def _exec_code_in_env(code: Union[str, types.CodeType], env: Dict[str, Any], fn_name: str) -> Callable[..., Any]: (source)

Undocumented

def _inspect_func_args(fn): (source)

Undocumented

def _unique_symbols(used: Sequence[str], *bases: str) -> Iterator[str]: (source)

Undocumented

def _update_argspec_defaults_into_env(spec, env): (source)

given a FullArgSpec, convert defaults to be symbol names in an env.

def _warnings_warn(message: Union[str, Warning], category: Optional[Type[Warning]] = None, stacklevel: int = 2): (source)

Undocumented

_SQLA_RE = (source)

Undocumented

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

Undocumented

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

Undocumented

Value
TypeVar('_E',
        bound=enum.Enum)

Undocumented

Value
TypeVar('_F',
        bound=Callable[..., Any])

Undocumented

Value
TypeVar('_Fn',
        bound='Callable[..., Any]')

Undocumented

Value
TypeVar('_GFD',
        bound='generic_fn_descriptor[Any]')

Undocumented

Value
TypeVar('_HM',
        bound='hybridmethod[Any]')

Undocumented

Value
TypeVar('_HP',
        bound='hybridproperty[Any]')

Undocumented

Value
TypeVar('_MA',
        bound='HasMemoized.memoized_attribute[Any]')

Undocumented

Value
TypeVar('_MP',
        bound='memoized_property[Any]')

Undocumented

Value
TypeVar('_PF')

Undocumented

Value
TypeVar('_T')

Undocumented

Value
TypeVar('_T_co',
        covariant=True)

Undocumented

Value
TypeVar('_TE')
_creation_order: int = (source)

Undocumented

_not_sa_pattern = (source)

Undocumented

_param_reg = (source)

Undocumented

Undocumented