Functions related to classes

introspection.get_subclasses(cls, include_abstract=False)

Collects all subclasses of the given class.

Parameters
  • cls – A base class

  • include_abstract – Whether abstract base classes should be included

Returns

A set of all subclasses

introspection.get_attributes(obj, include_weakref=False)

Returns a dictionary of all of obj’s attributes. This includes attributes stored in the object’s __dict__ as well as in __slots__.

Parameters
  • obj – The object whose attributes will be returned

  • include_weakref – Whether the value of the __weakref__ slot should be included in the result

Returns

A dict of {attr_name: attr_value}

introspection.safe_is_subclass(subclass, superclass)

A clone of issubclass() that returns False instead of throwing a TypeError.

New in version 1.2.

introspection.iter_slots(cls)

Iterates over all __slots__ of the given class, yielding (slot_name, slot_descriptor) tuples.

If a slot name is used more than once, all of them will be yielded in the order they appear in the class’s MRO.

Note that this function relies on the class-level __slots__ attribute - deleting or altering this attribute in any way may yield incorrect results.

Parameters

cls – The class whose slots to yield

Returns

An iterator yielding (slot_name, slot_descriptor) tuples

introspection.get_slot_names(cls)

Collects all of the given class’s __slots__, returning a set of slot names.

Parameters

cls – The class whose slots to collect

Returns

A set containing the names of all slots

introspection.get_slot_counts(cls)

Collects all of the given class’s __slots__, returning a dict of the form {slot_name: count}.

Parameters

cls – The class whose slots to collect

Returns

A collections.Counter counting the number of occurrences of each slot

introspection.get_slots(cls)

Collects all of the given class’s __slots__, returning a dict of the form {slot_name: slot_descriptor}.

If a slot name is used more than once, only the descriptor that shadows all other descriptors of the same name is returned.

Parameters

cls – The class whose slots to collect

Returns

A dict mapping slot names to descriptors