pak.util.decorators

Custom decorators.

cache(func=None, *, force_hashable=True, max_size=None, **kwargs)

Custom decorator used to cache function results.

Parameters:
  • func (callable) – The function whose results should be cached.

  • force_hashable (bool) –

    Whether unhashable arguments should be allowed.

    If True, then a TypeError is raised when unhashable arguments are passed.

    If False, then if unhashable arguments are passed, caching is completely bypassed.

  • max_size (int) –

    The maximum size of the least-reused cache.

    If None, then there is no limit, and cached values are never discarded.

  • **kwargs – Forwarded onto functools.lru_cache().

Returns:

The new function whose results will be cached.

Return type:

callable

class class_or_instance_method(class_method, instance_method=None)

Bases: object

A decorator to call either a class method or an instance method.

The __doc__ attribute is set to the __doc__ attribute of the associated class method.

This, similarly to classmethod, propagates other descriptors as well, allowing combinations of class_or_instance_method with property for example.

Parameters:
  • class_method (function) – The function for the class method.

  • instance_method (function or None) – The function for the instance method.

Examples

>>> import pak
>>> class MyClass:
...     @pak.util.class_or_instance_method
...     def method(cls):
...         return "class"
...
...     @method.instance_method
...     def method(self):
...         return "instance"
...
>>> MyClass.method()
'class'
>>> MyClass().method()
'instance'
class_method(class_method)

A decorator that sets the class method.

Parameters:

class_method (function) – The function for the class method.

Returns:

The descriptor with the newly set class method.

Return type:

class_or_instance_method

instance_method(instance_method)

A decorator that sets the instance method.

Warning

The instance method must be set, otherwise an error will be raised.

Parameters:

instance_method (function) – The function for the instance method.

Returns:

The descriptor with the newly set instance method.

Return type:

class_or_instance_method