Skip to content

decorators module

Class and function decorators.


binary_magic_config Config

Config of binary magic methods to be added to a class.

Config({
    "__eq__": {
        "func": "<ufunc 'equal'>"
    },
    "__ne__": {
        "func": "<ufunc 'not_equal'>"
    },
    "__lt__": {
        "func": "<ufunc 'less'>"
    },
    "__gt__": {
        "func": "<ufunc 'greater'>"
    },
    "__le__": {
        "func": "<ufunc 'less_equal'>"
    },
    "__ge__": {
        "func": "<ufunc 'greater_equal'>"
    },
    "__add__": {
        "func": "<ufunc 'add'>"
    },
    "__sub__": {
        "func": "<ufunc 'subtract'>"
    },
    "__mul__": {
        "func": "<ufunc 'multiply'>"
    },
    "__pow__": {
        "func": "<ufunc 'power'>"
    },
    "__mod__": {
        "func": "<ufunc 'remainder'>"
    },
    "__floordiv__": {
        "func": "<ufunc 'floor_divide'>"
    },
    "__truediv__": {
        "func": "<ufunc 'true_divide'>"
    },
    "__radd__": {
        "func": "<function <lambda> at 0x7f7d83b60e18>"
    },
    "__rsub__": {
        "func": "<function <lambda> at 0x7f7d83b60ea0>"
    },
    "__rmul__": {
        "func": "<function <lambda> at 0x7f7d83b60f28>"
    },
    "__rpow__": {
        "func": "<function <lambda> at 0x7f7d83b66048>"
    },
    "__rmod__": {
        "func": "<function <lambda> at 0x7f7d83b660d0>"
    },
    "__rfloordiv__": {
        "func": "<function <lambda> at 0x7f7d83b66158>"
    },
    "__rtruediv__": {
        "func": "<function <lambda> at 0x7f7d83b661e0>"
    },
    "__and__": {
        "func": "<ufunc 'bitwise_and'>"
    },
    "__or__": {
        "func": "<ufunc 'bitwise_or'>"
    },
    "__xor__": {
        "func": "<ufunc 'bitwise_xor'>"
    },
    "__rand__": {
        "func": "<function <lambda> at 0x7f7d83b66268>"
    },
    "__ror__": {
        "func": "<function <lambda> at 0x7f7d83b662f0>"
    },
    "__rxor__": {
        "func": "<function <lambda> at 0x7f7d83b66378>"
    }
})

unary_magic_config Config

Config of unary magic methods to be added to a class.

Config({
    "__neg__": {
        "func": "<ufunc 'negative'>"
    },
    "__pos__": {
        "func": "<ufunc 'positive'>"
    },
    "__abs__": {
        "func": "<ufunc 'absolute'>"
    },
    "__invert__": {
        "func": "<ufunc 'invert'>"
    }
})

attach_binary_magic_methods function

attach_binary_magic_methods(
    translate_func,
    config=None
)

Class decorator to add binary magic methods to a class.

translate_func should

  • take self, other, and unary function,
  • perform computation, and
  • return the result.

config defaults to binary_magic_config and should contain target method names (keys) and dictionaries (values) with the following keys:

  • func: Function that combines two array-like objects.

attach_unary_magic_methods function

attach_unary_magic_methods(
    translate_func,
    config=None
)

Class decorator to add unary magic methods to a class.

translate_func should

  • take self and unary function,
  • perform computation, and
  • return the result.

config defaults to unary_magic_config and should contain target method names (keys) and dictionaries (values) with the following keys:

  • func: Function that transforms one array-like object.

cached_method function

cached_method(
    *args,
    maxsize=128,
    typed=False,
    **flags
)

Extends custom_method() with caching.

Internally uses functools.lru_cache.

Disables caching if should_cache() yields False or a non-hashable object as argument has been passed.

See notes on cached_property.


custom_method function

custom_method(
    *args,
    **flags
)

Custom extensible method that stores function and flags as attributes.

Can be called both as

>>> @cached_method
... def user_function(): pass
and
>>> @cached_method(maxsize=128, typed=False, a=0, b=0)  # flags
... def user_function(): pass


should_cache function

should_cache(
    func_name,
    instance,
    func=None,
    **flags
)

Check whether to cache the method/property based on a range of conditions defined under caching in settings.

Each condition has its own rank. A narrower condition has a lower (better) rank than a broader condition. All supplied keys are checked, and if any condition fails, it's assigned to the highest (worst) rank.

Here's the condition ranking:

0) instance and func 1) instance and flags 2) instance 3) cls and func 4) cls and flags 5) cls 6) base_cls and func 7) base_cls and flags 8) base_cls 9) func and flags 10) func 11) flags

This function goes through all conditions of type CacheCondition in whitelist and blacklist and finds the one with the lowest (best) rank. If the search yields the same rank for both lists, global caching flag enabled decides.

Usage

  • Let's evaluate various caching conditions:
>>> import vectorbt as vbt

>>> class A:
...     @cached_property(my_flag=True)
...     def f(self):
...         return None

>>> class B(A):
...     @cached_property(my_flag=False)
...     def f(self):
...         return None

>>> a = A()
>>> b = B()

>>> vbt.CacheCondition(instance=a, func='f')  # A.f
>>> vbt.CacheCondition(instance=b, func='f')  # B.f
>>> vbt.CacheCondition(instance=a, flags=dict(my_flag=True))  # A.f
>>> vbt.CacheCondition(instance=a, flags=dict(my_flag=False))  # none
>>> vbt.CacheCondition(instance=b, flags=dict(my_flag=False))  # B.f
>>> vbt.CacheCondition(instance=a)  # A.f
>>> vbt.CacheCondition(instance=b)  # B.f
>>> vbt.CacheCondition(cls=A)  # A.f
>>> vbt.CacheCondition(cls=B)  # B.f
>>> vbt.CacheCondition(base_cls=A)  # A.f and B.f
>>> vbt.CacheCondition(base_cls=B)  # B.f
>>> vbt.CacheCondition(base_cls=A, flags=dict(my_flag=False))  # B.f
>>> vbt.CacheCondition(func=A.f)  # A.f
>>> vbt.CacheCondition(func=B.f)  # B.f
>>> vbt.CacheCondition(func='f')  # A.f and B.f
>>> vbt.CacheCondition(func='f', flags=dict(my_flag=False))  # B.f
>>> vbt.CacheCondition(flags=dict(my_flag=True))  # A.f

CacheCondition class

CacheCondition(
    instance=None,
    func=None,
    cls=None,
    base_cls=None,
    flags=None,
    rank=None
)

Caching condition for the use in should_cache().

Superclasses

  • builtins.tuple

base_cls property

Base class of the class or its name (case-sensitive).


cls property

Class of the instance or its name (case-sensitive).


flags property

Flags to check for in method/property's flags.


func property

Method/property or its name (case-sensitive).


instance property

Class instance the method/property is bound to.


rank property

Rank to override the default rank.


cached_methodT class

cached_methodT(
    *args,
    **kwargs
)

Base class for protocol classes. Protocol classes are defined as::

class Proto(Protocol):
    def meth(self) -> int:
        ...

Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing), for example::

class C

def meth(self) -> int:
    return 0

def func(x: Proto) -> int: return x.meth()

func(C()) # Passes static type check

See PEP 544 for details. Protocol classes decorated with @typing_extensions.runtime act as simple-minded runtime protocol that checks only the presence of given attributes, ignoring their type signatures.

Protocol classes can be generic, they are defined as::

class GenProto(Protocol[T]):
    def meth(self) -> T:
        ...

Superclasses


attrname class variable


clear_cache class variable


lock class variable


maxsize class variable


name class variable


typed class variable


cached_property class

cached_property(
    func,
    **flags
)

Extends custom_property with caching.

Similar to functools.cached_property, but without replacing the original attribute to be able to re-compute whenever needed.

Disables caching if should_cache() yields False.

Cache can be cleared by calling clear_cache with instance as argument.

!!! note: Assumes that the instance (provided as self) won't change. If calculation depends upon object attributes that can be changed, it won't notice the change.

Superclasses


attrname property

Get name of cached attribute.


clear_cache method

cached_property.clear_cache(
    instance
)

Clear the cache for this property belonging to instance.


class_or_instancemethod class

class_or_instancemethod(
    *args,
    **kwargs
)

Function decorator that binds self to a class if the function is called as class method, otherwise to an instance.

Superclasses

  • builtins.classmethod

class_or_instanceproperty class

class_or_instanceproperty(
    func
)

Property that binds self to a class if the function is called as class method, otherwise to an instance.


classproperty class

classproperty(
    func
)

Property that can be called on a class.


custom_methodT class

custom_methodT(
    *args,
    **kwargs
)

Base class for protocol classes. Protocol classes are defined as::

class Proto(Protocol):
    def meth(self) -> int:
        ...

Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing), for example::

class C

def meth(self) -> int:
    return 0

def func(x: Proto) -> int: return x.meth()

func(C()) # Passes static type check

See PEP 544 for details. Protocol classes decorated with @typing_extensions.runtime act as simple-minded runtime protocol that checks only the presence of given attributes, ignoring their type signatures.

Protocol classes can be generic, they are defined as::

class GenProto(Protocol[T]):
    def meth(self) -> T:
        ...

Superclasses

  • typing_extensions.Protocol

Subclasses


flags class variable


func class variable


custom_property class

custom_property(
    func,
    **flags
)

Custom property that stores function and flags as attributes.

Can be called both as

>>> @custom_property
... def user_function(self): pass
and
>>> @custom_property(a=0, b=0)  # flags
... def user_function(self): pass

Note

custom_property instances belong to classes, not class instances. Thus changing the property, for example, by disabling caching, will do the same for each instance of the class where the property has been defined.

Subclasses