mode.utils.objects

Object utilities.

mode.utils.objects.FieldMapping

alias of typing.Mapping

mode.utils.objects.DefaultsMapping

alias of typing.Mapping

exception mode.utils.objects.InvalidAnnotation

Raised by annotations() when encountering an invalid type.

class mode.utils.objects.Unordered(value: _T)

Shield object from being ordered in heapq/__le__/etc.

class mode.utils.objects.KeywordReduce

Mixin class for objects that can be “pickled”.

“Pickled” means the object can be serialiazed using the Python binary serializer – the pickle module.

Python objects are made pickleable through defining the __reduce__ method, that returns a tuple of: (restore_function, function_starargs):

class X:

    def __init__(self, arg1, kw1=None):
        self.arg1 = arg1
        self.kw1 = kw1

    def __reduce__(self) -> Tuple[Callable, Tuple[Any, ...]]:
        return type(self), (self.arg1, self.kw1)

This is tedious since this means you cannot accept **kwargs in the constructur, so what we do is define a __reduce_keywords__ argument that returns a dict instead:

class X:

    def __init__(self, arg1, kw1=None):
        self.arg1 = arg1
        self.kw1 = kw1

    def __reduce_keywords__(self) -> Mapping[str, Any]:
        return {
            'arg1': self.arg1,
            'kw1': self.kw1,
        }
mode.utils.objects.qualname(obj: Any) → str

Get object qualified name.

mode.utils.objects.shortname(obj: Any) → str

Get object name (non-qualified).

mode.utils.objects.canoname(obj: Any, *, main_name: str = None) → str

Get qualname of obj, trying to resolve the real name of __main__.

mode.utils.objects.canonshortname(obj: Any, *, main_name: str = None) → str

Get non-qualified name of obj, resolve real name of __main__.

mode.utils.objects.annotations(cls: Type, *, stop: Type = <class 'object'>, invalid_types: Set = None, alias_types: Mapping = None, skip_classvar: bool = False, globalns: Dict[str, Any] = None, localns: Dict[str, Any] = None) → Tuple[Mapping[str, Type], Mapping[str, Any]]

Get class field definition in MRO order.

Parameters
  • cls – Class to get field information from.

  • stop – Base class to stop at (default is object).

  • invalid_types – Set of types that if encountered should raise InvalidAnnotation (does not test for subclasses).

  • alias_types – Mapping of original type to replacement type.

  • skip_classvar – Skip attributes annotated with typing.ClassVar.

  • globalns – Global namespace to use when evaluating forward references (see typing.ForwardRef).

  • localns – Local namespace to use when evaluating forward references (see typing.ForwardRef).

Returns

Tuple with two dictionaries,

the first containing a map of field names to their types, the second containing a map of field names to their default value. If a field is not in the second map, it means the field is required.

Return type

Tuple[FieldMapping, DefaultsMapping]

Raises

InvalidAnnotation – if a list of invalid types are provided and an invalid type is encountered.

Examples

>>> class Point:
...    x: float
...    y: float

>>> class 3DPoint(Point):
...     z: float = 0.0

>>> fields, defaults = annotations(3DPoint)
>>> fields
{'x': float, 'y': float, 'z': 'float'}
>>> defaults
{'z': 0.0}
mode.utils.objects.eval_type(typ: Any, globalns: Dict[str, Any] = None, localns: Dict[str, Any] = None, invalid_types: Set = None, alias_types: Mapping = None) → Type

Convert (possible) string annotation to actual type.

Examples

>>> eval_type('List[int]') == typing.List[int]
mode.utils.objects.iter_mro_reversed(cls: Type, stop: Type) → Iterable[Type]

Iterate over superclasses, in reverse Method Resolution Order.

The stop argument specifies a base class that when seen will stop iterating (well actually start, since this is in reverse, see Example for demonstration).

Parameters
  • cls (Type) – Target class.

  • stop (Type) – A base class in which we stop iteration.

Notes

The last item produced will be the class itself (cls).

Examples

>>> class A: ...
>>> class B(A): ...
>>> class C(B): ...
>>> list(iter_mro_reverse(C, object))
[A, B, C]
>>> list(iter_mro_reverse(C, A))
[B, C]
Yields

Iterable[Type] – every class.

mode.utils.objects.guess_polymorphic_type(typ: Type, *, set_types: Tuple[Type, ...] = (typing.AbstractSet, typing.FrozenSet, typing.MutableSet, typing.Set, <class 'collections.abc.Set'>), list_types: Tuple[Type, ...] = (typing.List, typing.Sequence, typing.MutableSequence, <class 'collections.abc.Sequence'>), tuple_types: Tuple[Type, ...] = (typing.Tuple, ), dict_types: Tuple[Type, ...] = (typing.Dict, typing.Mapping, typing.MutableMapping, <class 'collections.abc.Mapping'>)) → Tuple[Type, Type]

Try to find the polymorphic and concrete type of an abstract type.

Returns tuple of (polymorphic_type, concrete_type).

Examples

>>> guess_polymorphic_type(List[int])
(list, int)
>>> guess_polymorphic_type(Optional[List[int]])
(list, int)
>>> guess_polymorphic_type(MutableMapping[int, str])
(dict, str)
mode.utils.objects.label(s: Any) → str

Return the name of an object as string.

mode.utils.objects.shortlabel(s: Any) → str

Return the shortened name of an object as string.

class mode.utils.objects.cached_property(fget: Callable[Any, RT], fset: Callable[[Any, RT], RT] = None, fdel: Callable[[Any, RT], None] = None, doc: str = None, class_attribute: str = None)

Cached property.

A property descriptor that caches the return value of the get function.

Examples

@cached_property
def connection(self):
    return Connection()

@connection.setter  # Prepares stored value
def connection(self, value):
    if value is None:
        raise TypeError('Connection must be a connection')
    return value

@connection.deleter
def connection(self, value):
    # Additional action to do at del(self.attr)
    if value is not None:
        print(f'Connection {value!r} deleted')
is_set(obj: Any) → bool
setter(fset: Callable[[Any, RT], RT]) → mode.utils.objects.cached_property
deleter(fdel: Callable[[Any, RT], None]) → mode.utils.objects.cached_property