snakeoil.klass module

common class implementations, and optimizations

The functionality contained within this module is of primary use for building classes themselves and cutting down on a significant amount of boilerplate involved in writing classes.

snakeoil.klass.DirProxy(target)[source]
snakeoil.klass.GetAttrProxy(target)[source]
class snakeoil.klass.SlotsPicklingMixin[source]

Bases: object

Default pickling support for classes that use __slots__.

class snakeoil.klass.alias(*aliases)[source]

Bases: object

Decorator for making methods callable through aliases.

This decorator must be used inside a class decorated with @aliased.

Example usage:

>>> from snakeoil.klass import aliased, alias
>>> @aliased
>>> class Speak:
...     @alias('yell', 'scream')
...     def shout(message):
...         return message.upper()
>>>
>>> speak = Speak()
>>> assert speak.shout('foo') == speak.yell('foo') == speak.scream('foo')
snakeoil.klass.alias_attr(target_attr)[source]

return a property that will alias access to target_attr

target_attr can be multiple getattrs in addition- x.y.z is valid for example

Example Usage:

>>> from snakeoil.klass import alias_attr
>>> class foo:
...
...   seq = (1,2,3)
...
...   def __init__(self, a=1):
...     self.a = a
...
...   b = alias_attr("a")
...   recursive = alias_attr("seq.__hash__")
>>>
>>> o = foo()
>>> print(o.a)
1
>>> print(o.b)
1
>>> print(o.recursive == foo.seq.__hash__)
True
snakeoil.klass.alias_method(attr, name=None, doc=None)[source]

at runtime, redirect to another method

This is primarily useful for when compatibility, or a protocol requires you to have the same functionality available at multiple spots- for example dict.has_key() and dict.__contains__().

Parameters:
  • attr – attribute to redirect to

  • name__name__ to force for the new method if desired

  • doc__doc__ to force for the new method if desired

>>> from snakeoil.klass import alias_method
>>> class foon:
...   def orig(self):
...     return 1
...   alias = alias_method("orig")
>>> obj = foon()
>>> assert obj.orig() == obj.alias()
>>> assert obj.alias() == 1
snakeoil.klass.aliased(cls)[source]

Class decorator used in combination with @alias method decorator.

snakeoil.klass.cached_hash(func)[source]

decorator to cache the hash value.

It’s important to note that you should only be caching the hash value if you know it cannot change.

>>> from snakeoil.klass import cached_hash
>>> class foo:
...   def __init__(self):
...     self.hash_invocations = 0
...
...   @cached_hash
...   def __hash__(self):
...     self.hash_invocations += 1
...     return 12345
>>>
>>> f = foo()
>>> assert f.hash_invocations == 0
>>> assert hash(f) == 12345
>>> assert f.hash_invocations == 1
>>> assert hash(f) == 12345        # note we still get the same value
>>> assert f.hash_invocations == 1 # and that the function was invoked only once.
snakeoil.klass.cached_property(func: ~typing.Callable[[~typing.Any], ~snakeoil.klass.T], kls=<function _internal_jit_attr>, use_cls_setattr=False) T[source]

like property, just with caching

This is usable in classes that aren’t using slots; it exploits python lookup ordering such that on first access, the function is invoked generating the desired attribute. It then assigns that content to the same name as the property- directly into the instance dictionary. Subsequent accesses will find the value in the instance dictionary first- essentially just as fast as normal attribute access, just w/ the ability to generate the instance on first access (or to wipe the attribute and force a regeneration).

Example Usage:

>>> from snakeoil.klass import cached_property
>>> class foo:
...
...   @cached_property
...   def attr(self):
...     print("invoked")
...     return 1
>>>
>>> obj = foo()
>>> print(obj.attr)
invoked
1
>>> print(obj.attr)
1
snakeoil.klass.cached_property_named(name: str, kls=<function _internal_jit_attr>, use_cls_setattr=False)[source]

variation of cached_property, just with the ability to explicitly set the attribute name

Primarily of use for when the functor it’s wrapping has a generic name ( functools.partial instances for example). Example Usage:

>>> from snakeoil.klass import cached_property_named
>>> class foo:
...
...   @cached_property_named("attr")
...   def attr(self):
...     print("invoked")
...     return 1
>>>
>>> obj = foo()
>>> print(obj.attr)
invoked
1
>>> print(obj.attr)
1
snakeoil.klass.generic_equality(name, bases, scope, real_type=<class 'type'>, eq=<function generic_attr_eq>, ne=<function generic_attr_ne>)[source]

metaclass generating __eq__/__ne__ methods from an attribute list

The consuming class must set a class attribute named __attr_comparison__ that is a sequence that lists the attributes to compare in determining equality or a string naming the class attribute to pull the list of attributes from (e.g. ‘__slots__’).

Raise:

TypeError if __attr_comparison__ is incorrectly defined

>>> from snakeoil.klass import generic_equality
>>> class foo(metaclass=generic_equality):
...   __attr_comparison__ = ("a", "b", "c")
...   def __init__(self, a=1, b=2, c=3):
...     self.a, self.b, self.c = a, b, c
>>>
>>> assert foo() == foo()
>>> assert not (foo() != foo())
>>> assert foo(1,2,3) == foo()
>>> assert foo(3, 2, 1) != foo()
snakeoil.klass.immutable_instance(name, bases, scope, real_type=<class 'type'>)[source]

metaclass that makes instances of this class effectively immutable

It still is possible to do object.__setattr__ to get around it during initialization, but usage of this class effectively prevents accidental modification, instead requiring explicit modification.

snakeoil.klass.inject_immutable_instance(scope)[source]

inject immutable __setattr__ and __delattr__ implementations

see immutable_instance for further details

Parameters:

scope – mapping to modify, inserting __setattr__ and __delattr__ methods if they’re not yet defined.

snakeoil.klass.inject_richcmp_methods_from_cmp(scope)[source]

class namespace modifier injecting richcmp methods that rely on __cmp__ for py3k compatibility

Note that this just injects generic implementations such as generic_lt(); if a method already exists, it will not override it. This behavior is primarily beneficial if the developer wants to optimize one specific method- __lt__ for sorting reasons for example, but performance is less of a concern for the other rich comparison methods.

Example usage:

>>> from snakeoil.klass import inject_richcmp_methods_from_cmp
>>> from snakeoil.compatibility import cmp
>>> class foo:
...
...   # note that for this example, we inject always since we're
...   # explicitly accessing __ge__ methods- under py2k, they wouldn't
...   # exist (__cmp__ would be sufficient).
...
...   # add the generic rich comparsion methods to the local class namespace
...   inject_richcmp_methods_from_cmp(locals())
...
...   def __init__(self, a, b):
...     self.a, self.b = a, b
...
...   def __cmp__(self, other):
...     c = cmp(self.a, other.a)
...     if c == 0:
...       c = cmp(self.b, other.b)
...     return c
>>>
>>> assert foo(1, 2).__ge__(foo(1, 1))
>>> assert foo(1, 1).__eq__(foo(1, 1))
Parameters:

scope – the modifiable scope of a class namespace to work on

snakeoil.klass.instance_attrgetter

alias of chained_getter

snakeoil.klass.jit_attr(func: ~typing.Callable[[~typing.Any], ~snakeoil.klass.T], kls=<function _internal_jit_attr>, uncached_val: ~typing.Any = <class 'snakeoil.klass._singleton_kls'>) T[source]

decorator to JIT generate, and cache the wrapped functions result in ‘_’ + func.__name__ on the instance.

Parameters:
  • func – function to wrap

  • kls – internal arg, overridden if you need a tweaked version of _internal_jit_attr

  • uncached_val – the value to treat as missing/force regeneration when accessing the instance. Note this normally defaults to a singleton that will not be in use anywhere else.

Returns:

functor implementing the described behaviour

snakeoil.klass.jit_attr_ext_method(func_name: str, stored_attr_name: str, use_cls_setattr=False, kls=<function _internal_jit_attr>, uncached_val: ~typing.Any = <class 'snakeoil.klass._singleton_kls'>, doc=None)[source]

Decorator handing maximal control of attribute JIT’ing to the invoker.

See internal_jit_attr for documentation of the misc params.

Generally speaking, you only need this when you are doing something rather special.

snakeoil.klass.jit_attr_named(stored_attr_name: str, use_cls_setattr=False, kls=<function _internal_jit_attr>, uncached_val: ~typing.Any = <class 'snakeoil.klass._singleton_kls'>, doc=None)[source]

Version of jit_attr() decorator that allows for explicit control over the attribute name used to store the cache value.

See _internal_jit_attr for documentation of the misc params.

snakeoil.klass.jit_attr_none(func: ~typing.Callable[[~typing.Any], ~snakeoil.klass.T], kls=<function _internal_jit_attr>) T[source]

Version of jit_attr() decorator that forces the uncached_val to None.

This is mainly useful so that if any out of band forced regeneration of the value, they know they just have to write None to the attribute to force regeneration.

snakeoil.klass.patch(target, external_decorator=None)[source]

Simplified monkeypatching via decorator.

Parameters:
  • target – target method to replace

  • external_decorator – decorator used on target method, e.g. classmethod or staticmethod

Example usage (that’s entirely useless):

>>> import math
>>> from snakeoil.klass import patch
>>> @patch('math.ceil')
>>> def ceil(orig_ceil, n):
...   return math.floor(n)
>>> assert math.ceil(0.1) == 0
snakeoil.klass.reflective_hash(attr)[source]

default __hash__ implementation that returns a pregenerated hash attribute

Parameters:

attr – attribute name to pull the hash from on the instance

Returns:

hash value for instance this func is used in.

snakeoil.klass.static_attrgetter

alias of attrgetter

snakeoil.klass.steal_docs(target, ignore_missing=False, name=None)[source]

decorator to steal __doc__ off of a target class or function

Specifically when the target is a class, it will look for a member matching the functors names from target, and clones those docs to that functor; otherwise, it will simply clone the targeted function’s docs to the functor.

Parameters:
  • target – class or function to steal docs from

  • ignore_missing – if True, it’ll swallow the exception if it cannot find a matching method on the target_class. This is rarely what you want- it’s mainly useful for cases like dict.has_key, where it exists in py2k but doesn’t in py3k

  • name – function name from class to steal docs from, by default the name of the decorated function is used; only used when the target is a class name

Example Usage:

>>> from snakeoil.klass import steal_docs
>>> class foo(list):
...   @steal_docs(list)
...   def extend(self, *a):
...     pass
>>>
>>> f = foo([1,2,3])
>>> assert f.extend.__doc__ == list.extend.__doc__