pyTooling.Attributes

This Python module offers the base implementation of .NET-like attributes realized with class-based Python decorators. This module comes also with a mixin-class to ease using classes having annotated methods.

The annotated data is stored as instances of Attribute classes in an additional field per class, method or function. By default, this field is called __pyattr__.

Hint

See high-level help for explanations and usage examples.

Submodules

Variables

Classes

  • AttributeScope: An enumeration of possible entities an attribute can be applied to.

  • Attribute: Base-class for all pyTooling attributes.

  • SimpleAttribute: Base-class for all pyTooling attributes.


Variables

pyTooling.Attributes.Entity

A type variable for functions, methods or classes.

~Entity
pyTooling.Attributes.TAttr

A type variable for Attribute.

~TAttr
pyTooling.Attributes.TAttributeFilter

A type hint for a predicate parameter that accepts either a single Attribute or an iterable of those.

typing.Union[typing.Type[~TAttr], typing.Iterable[typing.Type[~TAttr]], NoneType]

alias of Type[TAttr] | Iterable[Type[TAttr]] | None

pyTooling.Attributes.ATTRIBUTES_MEMBER_NAME

Field name on entities (function, class, method) to store pyTooling.Attributes.

'__pyattr__'

Classes

class pyTooling.Attributes.AttributeScope(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

An enumeration of possible entities an attribute can be applied to.

Values of this enumeration can be merged (or-ed) if an attribute can be applied to multiple language entities. Supported language entities are: classes, methods or functions. Class fields or module variables are not supported.

Inheritance

Inheritance diagram of AttributeScope

Class = 1

Attribute can be applied to classes.

Method = 2

Attribute can be applied to methods.

Function = 4

Attribute can be applied to functions.

Any = 7

Attribute can be applied to any language entity.

static _generate_next_value_(name, start, count, last_values)

Generate the next value when not given.

name: the name of the member start: the initial start value or None count: the number of existing members last_values: the last value assigned or None

__format__(format_spec, /)

Convert to a string according to format_spec.

__str__()

Return repr(self).

__repr__()

Return repr(self).

__or__(other)

Return self|value.

__and__(other)

Return self&value.

__xor__(other)

Return self^value.

__ror__(other)

Return value|self.

__rand__(other)

Return value&self.

__rxor__(other)

Return value^self.

__invert__()

~self

__new__(value)
__hash__()

Return hash(self).

__getattribute__(name, /)

Return getattr(self, name).

__lt__(value, /)

Return self<value.

__le__(value, /)

Return self<=value.

__eq__(value, /)

Return self==value.

__ne__(value, /)

Return self!=value.

__gt__(value, /)

Return self>value.

__ge__(value, /)

Return self>=value.

__add__(value, /)

Return self+value.

__radd__(value, /)

Return value+self.

__sub__(value, /)

Return self-value.

__rsub__(value, /)

Return value-self.

__mul__(value, /)

Return self*value.

__rmul__(value, /)

Return value*self.

__mod__(value, /)

Return self%value.

__rmod__(value, /)

Return value%self.

__divmod__(value, /)

Return divmod(self, value).

__rdivmod__(value, /)

Return divmod(value, self).

__pow__(value, mod=None, /)

Return pow(self, value, mod).

__rpow__(value, mod=None, /)

Return pow(value, self, mod).

__neg__()

-self

__pos__()

+self

__abs__()

abs(self)

__bool__()

True if self else False

__lshift__(value, /)

Return self<<value.

__rlshift__(value, /)

Return value<<self.

__rshift__(value, /)

Return self>>value.

__rrshift__(value, /)

Return value>>self.

__int__()

int(self)

__float__()

float(self)

__floordiv__(value, /)

Return self//value.

__rfloordiv__(value, /)

Return value//self.

__truediv__(value, /)

Return self/value.

__rtruediv__(value, /)

Return value/self.

__index__()

Return self converted to an integer, if self is suitable for use as an index into a list.

conjugate()

Returns self, the complex conjugate of any int.

bit_length()

Number of bits necessary to represent self in binary.

>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
bit_count()

Number of ones in the binary representation of the absolute value of self.

Also known as the population count.

>>> bin(13)
'0b1101'
>>> (13).bit_count()
3
to_bytes(length=1, byteorder='big', *, signed=False)

Return an array of bytes representing an integer.

length

Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes. Default is length 1.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value. Default is to use ‘big’.

signed

Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.

from_bytes(byteorder='big', *, signed=False)

Return the integer represented by the given array of bytes.

bytes

Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value. Default is to use ‘big’.

signed

Indicates whether two’s complement is used to represent the integer.

as_integer_ratio()

Return a pair of integers, whose ratio is equal to the original int.

The ratio is in lowest terms and has a positive denominator.

>>> (10).as_integer_ratio()
(10, 1)
>>> (-10).as_integer_ratio()
(-10, 1)
>>> (0).as_integer_ratio()
(0, 1)
__trunc__()

Truncating an Integral returns itself.

__floor__()

Flooring an Integral returns itself.

__ceil__()

Ceiling of an Integral returns itself.

__round__()

Rounding an Integral returns itself.

Rounding with an ndigits argument also returns an integer.

__sizeof__()

Returns size in memory, in bytes.

is_integer()

Returns True. Exists for duck type compatibility with float.is_integer.

real

the real part of a complex number

imag

the imaginary part of a complex number

numerator

the numerator of a rational number in lowest terms

denominator

the denominator of a rational number in lowest terms

_numeric_repr_()

Return the canonical string representation of the object.

For many object types, including most builtins, eval(repr(obj)) == obj.

classmethod _iter_member_by_value_(value)

Extract all members from the value in definition (i.e. increasing value) order.

classmethod _iter_member_(value)

Extract all members from the value in definition (i.e. increasing value) order.

classmethod _iter_member_by_def_(value)

Extract all members from the value in definition order.

classmethod _missing_(value)

Create a composite member containing all canonical members present in value.

If non-member values are present, result depends on _boundary_ setting.

__contains__(other)

Returns True if self has at least the same flags set as other.

__iter__()

Returns flags in definition order.

__len__()

Return the number of members (no aliases)

__dir__()

Returns public methods and other interesting attributes.

__init__(*args, **kwds)
__reduce_ex__(proto)

Helper for pickle.

class pyTooling.Attributes.Attribute[source]

Base-class for all pyTooling attributes.

Inheritance

Inheritance diagram of Attribute

_functions: ClassVar[List[Any]] = []

List of functions, this Attribute was attached to.

_classes: ClassVar[List[Any]] = []

List of classes, this Attribute was attached to.

_methods: ClassVar[List[Any]] = []

List of methods, this Attribute was attached to.

_scope: ClassVar[AttributeScope] = 7

Allowed language construct this attribute can be used with.

classmethod __init_subclass__(**kwargs)[source]

Ensure each derived class has its own instance of _functions, _classes and _methods to register the usage of that Attribute.

Return type:

None

Parameters:

kwargs (Any)

__call__(entity)[source]

Attributes get attached to an entity (function, class, method) and an index is updated at the attribute for reverse lookups.

Parameters:

entity (TypeVar(Entity, bound= Union[Type, Callable])) – Entity (function, class, method), to attach an attribute to.

Return type:

TypeVar(Entity, bound= Union[Type, Callable])

Returns:

Same entity, with attached attribute.

Raises:

TypeError – If parameter ‘entity’ is not a function, class nor method.

static _AppendAttribute(entity, attribute)[source]

Append an attribute to a language entity (class, method, function).

Hint

This method can be used in attribute groups to apply multiple attributes within __call__ method.

class GroupAttribute(Attribute):
  def __call__(self, entity: Entity) -> Entity:
    self._AppendAttribute(entity, SimpleAttribute(...))
    self._AppendAttribute(entity, SimpleAttribute(...))

    return entity
Parameters:
Raises:

TypeError – If parameter ‘entity’ is not a class, method or function.

Return type:

None

classmethod GetFunctions(scope=None)[source]

Return a generator for all functions, where this attribute is attached to.

The resulting item stream can be filtered by:
  • scope - when the item is a nested class in scope scope.

Parameters:

scope (Optional[Type]) – Undocumented.

Return type:

Generator[TypeVar(TAttr, bound= Attribute), None, None]

Returns:

A sequence of functions where this attribute is attached to.

classmethod GetClasses(scope=None, subclassOf=None)[source]

Return a generator for all classes, where this attribute is attached to.

The resulting item stream can be filtered by:
  • scope - when the item is a nested class in scope scope.

  • subclassOf - when the item is a subclass of subclassOf.

Parameters:
Return type:

Generator[TypeVar(TAttr, bound= Attribute), None, None]

Returns:

A sequence of classes where this attribute is attached to.

classmethod GetMethods(scope=None)[source]

Return a generator for all methods, where this attribute is attached to.

The resulting item stream can be filtered by:
  • scope - when the item is a nested class in scope scope.

Parameters:

scope (Optional[Type]) – Undocumented.

Return type:

Generator[TypeVar(TAttr, bound= Attribute), None, None]

Returns:

A sequence of methods where this attribute is attached to.

classmethod GetAttributes(method, includeSubClasses=True)[source]

Returns attached attributes of this kind for a given method.

Parameters:
  • method (MethodType)

  • includeSubClasses (bool)

Return type:

Tuple[Attribute, ...]

Returns:

Raises:

TypeError

class pyTooling.Attributes.SimpleAttribute(*args, **kwargs)[source]

Inheritance

Inheritance diagram of SimpleAttribute

classmethod GetAttributes(method, includeSubClasses=True)

Returns attached attributes of this kind for a given method.

Parameters:
  • method (MethodType)

  • includeSubClasses (bool)

Return type:

Tuple[Attribute, ...]

Returns:

Raises:

TypeError

classmethod GetClasses(scope=None, subclassOf=None)

Return a generator for all classes, where this attribute is attached to.

The resulting item stream can be filtered by:
  • scope - when the item is a nested class in scope scope.

  • subclassOf - when the item is a subclass of subclassOf.

Parameters:
Return type:

Generator[TypeVar(TAttr, bound= Attribute), None, None]

Returns:

A sequence of classes where this attribute is attached to.

classmethod GetFunctions(scope=None)

Return a generator for all functions, where this attribute is attached to.

The resulting item stream can be filtered by:
  • scope - when the item is a nested class in scope scope.

Parameters:

scope (Optional[Type]) – Undocumented.

Return type:

Generator[TypeVar(TAttr, bound= Attribute), None, None]

Returns:

A sequence of functions where this attribute is attached to.

classmethod GetMethods(scope=None)

Return a generator for all methods, where this attribute is attached to.

The resulting item stream can be filtered by:
  • scope - when the item is a nested class in scope scope.

Parameters:

scope (Optional[Type]) – Undocumented.

Return type:

Generator[TypeVar(TAttr, bound= Attribute), None, None]

Returns:

A sequence of methods where this attribute is attached to.

static _AppendAttribute(entity, attribute)

Append an attribute to a language entity (class, method, function).

Hint

This method can be used in attribute groups to apply multiple attributes within __call__ method.

class GroupAttribute(Attribute):
  def __call__(self, entity: Entity) -> Entity:
    self._AppendAttribute(entity, SimpleAttribute(...))
    self._AppendAttribute(entity, SimpleAttribute(...))

    return entity
Parameters:
Raises:

TypeError – If parameter ‘entity’ is not a class, method or function.

Return type:

None

__call__(entity)

Attributes get attached to an entity (function, class, method) and an index is updated at the attribute for reverse lookups.

Parameters:

entity (TypeVar(Entity, bound= Union[Type, Callable])) – Entity (function, class, method), to attach an attribute to.

Return type:

TypeVar(Entity, bound= Union[Type, Callable])

Returns:

Same entity, with attached attribute.

Raises:

TypeError – If parameter ‘entity’ is not a function, class nor method.

classmethod __init_subclass__(**kwargs)

Ensure each derived class has its own instance of _functions, _classes and _methods to register the usage of that Attribute.

Return type:

None

Parameters:

kwargs (Any)

_classes: ClassVar[List[Any]] = []

List of classes, this Attribute was attached to.

_functions: ClassVar[List[Any]] = []

List of functions, this Attribute was attached to.

_methods: ClassVar[List[Any]] = []

List of methods, this Attribute was attached to.

_scope: ClassVar[AttributeScope] = 7

Allowed language construct this attribute can be used with.

__init__(*args, **kwargs)[source]
Return type:

None