Misc. functions

introspection.get_parameters(callable_)

Returns a list of parameters accepted by callable_.

Parameters

callable_ – The callable whose parameters to retrieve

Return type

List[Parameter]

Returns

A list of Parameter instances

introspection.common_ancestor(classes)

Finds the closest common parent class of the given classes. If called with an empty iterable, object is returned.

Parameters

classes (Iterable[type]) – An iterable of classes

Return type

type

Returns

The given classes’ shared parent class

introspection.create_class(name, bases=(), attrs={}, metaclass=None, **kwargs)

Creates a new class. This is similar to types.new_class(), except it calls resolve_bases() even in python versions <= 3.7. (And it has a different interface.)

Parameters
  • name (str) – The name of the new class

  • bases (Iterable, default: ()) – An iterable of bases classes

  • attrs (dict, default: {}) – A dict of class attributes

  • metaclass (Optional[Callable[…, Type[~T]]], default: None) – The metaclass, or None

  • kwargs (Any) – Keyword arguments to pass to the metaclass

Return type

Type[~T]

Returns

A new class

introspection.resolve_bases(bases)

Clone/backport of types.resolve_bases().

Parameters

bases (Iterable) – An iterable of bases, which may or may not be classes

Return type

tuple

Returns

A tuple of base classes

introspection.static_vars(obj)

Like vars(), but bypasses overridden __getattribute__ methods and (for the most part) __dict__ descriptors.

Warning

Currently, if obj is not a class, there is a chance that a class attribute named __dict__ can shadow the real __dict__:

>>> class Demo: __dict__ = 'oops'
...
>>> static_vars(Demo())
'oops'

This is because I can’t find a reliable way to access the real __dict__ from within python. As far as I can tell, it’s only possible through the C API.

Parameters

obj (Any) – An object

Return type

Mapping

Returns

The object’s __dict__

Raises

TypeError – If the object has no __dict__

introspection.static_copy(obj)

Creates a copy of the given object without invoking any of its methods - __new__, __init__, __copy__ or anything else.

How it works:

  1. A new instance of the same class is created by calling object.__new__(type(obj)).

  2. If obj has a __dict__, the new instance’s __dict__ is updated with its contents.

  3. All values stored in __slots__ (except for __dict__ and __weakref__) are assigned to the new object.

An exception are instances of builtin classes - these are copied by calling copy.copy().

New in version 1.1.

Parameters

obj (~T) – The object to copy

Return type

~T

introspection.static_hasattr(obj, attr_name)

Like the builtin hasattr(), except it doesn’t execute any __getattr__ or __getattribute__ functions and also tries to avoid invoking descriptors. (See static_vars() for more details.)

New in version 1.4.

Parameters
  • obj (Any) – The object whose attribute you want to find

  • attr_name (str) – The name of the attribute to find

Return type

bool

introspection.static_mro(cls)

Given a class as input, returns the class’s MRO without invoking any overridden __getattribute__ methods or __mro__ descriptors.

New in version 1.4.

Parameters

cls (type) – A class

Return type

Tuple[type]

introspection.resolve_identifier(identifier)

Given a string as input, returns the object referenced by it.

Example:

>>> resolve_identifier('introspection.Parameter')
<class 'introspection.parameter.Parameter'>

Note that this function will not import any modules; the relevant module must already be present in sys.modules.

If no matching object can be found, NameError is raised.

Parameters

identifier (str) – The identifier to resolve

Return type

object

Returns

The object referenced by the identifier

Raises

NameError – If the identifier doesn’t reference anything

introspection.is_sub_qualname(sub_name, base_name)

Given two dotted names as input, returns whether the first is a child of the second.

Examples:

>>> is_sub_qualname('foo.bar', 'foo')
True
>>> is_sub_qualname('foo', 'foo')
True
>>> is_sub_qualname('foo.bar', 'foo.qux')
False

New in version 1.5.

Return type

bool

introspection.is_abstract(obj)

Given an object as input, returns whether it is abstract. The following types are supported:

  • Functions: These are considered abstract if they have an __isabstractmethod__ property with the value True.

  • staticmethods and classmethods: Abstract if the underlying function is abstract.

  • propertys: Abstract if their getter, setter, or deleter is abstract.

  • Classes: Abstract if any of their attributes are abstract.

New in version 1.4.

Parameters

obj (Any) – The object to inspect

Return type

bool

introspection.iter_wrapped(function, stop=None)

Given a function as input, yields the function and all the functions it wraps.

Unwraps, but does not yield, instances of staticmethod and classmethod.

If stop is given, it must be a function that takes a function as input and returns a truth value. As soon as stop(function) returns a truthy result, the iteration stops. (function will not be yielded.)

New in version 1.4.

Parameters
introspection.unwrap(function, stop=None)

Like inspect.unwrap(), but always unwraps staticmethods and classmethods. (inspect.unwrap() only does this since 3.10)

If stop is given, it must be a function that takes a function as input and returns a truth value. As soon as stop(function.__wrapped__) returns a truthy result, the unwrapping stops.

New in version 1.4.

Parameters
introspection.extract_functions(obj)

Given a staticmethod, classmethod or property as input, returns a list of the contained functions:

>>> extract_functions(staticmethod(foo))
[<function foo at 0xdeadbeef>]
>>> extract_functions(property(get, set))
[<function get at 0xdeadbeef>, <function set at 0xdeadbeef>]
Return type

List[Callable]

introspection.rename(obj, name)

Updates the __name__ and __qualname__ of an object.

New in version 1.4.

Parameters
  • obj (Any) – The object to rename

  • name (str) – The new name for the object

Return type

None

introspection.wraps(wrapped_func, name=None, signature=None, remove_parameters=None)

Similar to functools.wraps(), but allows you to modify the function’s metadata.

New in version 1.4.

Parameters
  • wrapped_func (Callable) – The wrapped function

  • name (Optional[str], default: None) – A new name for the wrapper function

  • signature (Optional[Signature], default: None) – A new signature for the wrapper function

  • remove_parameters (Optional[Iterable[Union[str, int]]], default: None) – Parameter names or indices to remove from the wrapper function’s signature

Return type

Callable[[Callable], Callable]

introspection.camel_to_snake(camel)

Converts a camel-case name to a snake-case name.

Examples:

>>> camel_to_snake('FooBar')
'foo_bar'
>>> camel_to_snake('HTTPAdapater')
'http_adapter'

New in version 1.5.

Return type

str

introspection.snake_to_camel(snake)

Converts a snake-case name to a camel-case name.

Examples:

>>> snake_to_camel('foo_bar')
'FooBar'
>>> snake_to_camel('http_adapter')
'HttpAdapter'

New in version 1.5.

Return type

str

class introspection.super

Bases: super

A subclass of the builtin super that lets you invoke the setter and deleter of descriptors in a parent class.

Note

Keep in mind that the 0-argument form of super() is powered by magic. Python automatically inserts the relevant arguments if it sees a function call that looks exactly like super(). introspection.super() won’t work.

You either have to pass the required arguments manually, or use from introspection import super.

Example:

from introspection import super

class Parent:
    @property
    def attr(self):
        return self._attr

    @attr.setter
    def attr(self, value):
        self._attr = value

class Child(Parent):
    @Parent.attr.setter
    def attr(self, value):
        super().attr = value + 1

New in version 1.4.