snakeoil.klass package¶
Submodules¶
Module contents¶
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.
- class snakeoil.klass.ImmutableInstance(**kwargs)[source]¶
Bases:
objectClass that disables surface-level attribute modifications.
- class snakeoil.klass.SlotsPicklingMixin[source]¶
Bases:
objectDefault pickling support for classes that use __slots__.
- snakeoil.klass.abstractclassvar(_: type[T]) T[source]¶
mechanism to use with ClassVars to force abc.ABC to block creation if the subclass hasn’t set it.
This can be used like thus: >>> from typing import ClassVar >>> class foon(abc.ABC): … required_class_var: ClassVar[str] = abstractclassvar(str) … >>> >>> foon() Traceback (most recent call last):
File “<python-input-8>”, line 1, in <module> foon() ~~~~^^
TypeError: Can’t instantiate abstract class foon without an implementation for abstract method ‘required_class_var’
The error message implies a method when it’s not, but that is a limitation of abc.ABC. The point of this is to allow forcing that derivatives create the cvar, thus the trade off.
The mechanism currently is janky; you must pass in the type definition since it’s the only way to attach this information to the returned object, lieing to the type system that the value is type compatible while carrying the marker abc.ABC needs.
- 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.zis valid for exampleExample 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()anddict.__contains__().- Parameters:
attr – attribute to redirect to
name –
__name__to force for the new method if desireddoc –
__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.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.properties.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.combine_classes(kls: type, *extra: type) type[source]¶
Given a set of classes, combine this as if one had wrote the class by hand
This is primarily for composing metaclasses on the fly; this:
class foo(metaclass=combine_metaclasses(kls1, kls2, kls3)): pass
is the same as if you did this:
class mkls(kls1, kls2, kls3): pass class foo(metaclass=mkls): pass
- snakeoil.klass.copy_docs(target)[source]¶
Copy the docs and annotations off of the given target
This is used for implementations that look like something (the target), but do not actually invoke the the target.
If you’re just wrapping something- a true decorator- use functools.wraps
- snakeoil.klass.generic_equality(name, bases, scope, real_type=<class 'type'>, eq=<function GenericEquality.__eq__>, ne=<function <lambda>>)[source]¶
Deprecated. Use snakeoil.klass.GenericEquality instead.
metaclass generating __eq__/__ne__ methods from an attribute list
The consuming class is abstract until a layer sets a class attribute named __attr_comparison__ which is the list of attributes to compare.
This can optionally derived via passing compare_slots=True in the class creation.
- 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.get_attrs_of(obj: Any, weakref=False, suppressions: Iterable[str] = (), _sentinel=<object object>) Iterable[tuple[str, Any]][source]¶
yield the attributes of a given instance.
This handles both slotted and non slotted classes- slotted classes do not have __dict__. It also handles mixed derivations, a non slotted class that inherited from a slotted class.
For an ordered __dict__ class, the ordering is not honored in what this yields.
- Parameters:
weakref – by default, suppress that __weakref__ exists since it’s python internal bookkeeping. The only reason to enable this is for introspection tools; even state saving tools shouldn’t care about __weakref__
suppressions – attributes to suppress from the return. Use this as a way to avoid having to write a filter in the consumer- this already has to do filtering after all.
- snakeoil.klass.get_slot_of(cls: type) ClassSlotting[source]¶
Return the non-inherited slotting from a class, IE specifically what that definition set.
- snakeoil.klass.get_slots_of(kls: type) Iterable[ClassSlotting][source]¶
Visit a class MRO collecting all slotting
This cannot collect slotting of C objects- python builtins like object, or literal python C extensions, not unless they expose __slots__.
- snakeoil.klass.get_subclasses_of(cls: type, only_leaf_nodes=False, ABC: None | bool = None) Iterable[type][source]¶
yield the subclasses of the given class.
This walks the in memory tree of a class hierarchy, yield the subclasses of the given cls after optional filtering.
Note: this cannot work on metaclasses. Python doesn’t carry the necessary bookkeeping. The first level of a metaclass will be returned, but none of it’s derivative, and it’ll be treated as a leaf node- even if it isn’t.
- Parameters:
only_leaf_nodes – if True, only yield classes which have no subclasses
ABC – if True, only yield abstract classes. If False, only yield classes no longer abstract. If None- the default- do no filtering for ABC.
- snakeoil.klass.immutable_instance(name: str, bases: tuple[type], scope: dict[str, ~typing.Any], real_type=<class 'type'>) 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: dict[str, Any])[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.is_metaclass(cls: type) TypeGuard[type[type]][source]¶
discern if something is a metaclass. This intentionally ignores function based metaclasses
- snakeoil.klass.jit_attr(func: ~typing.Callable[[~typing.Any], ~snakeoil.klass.properties.T], kls=<function _internal_jit_attr>, uncached_val: ~typing.Any = <snakeoil.klass.properties.kls object>) 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_attruncached_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: Any = <snakeoil.klass.properties.kls object>, doc=None)[source]¶
Decorator handing maximal control of attribute JIT’ing to the invoker.
See
internal_jit_attrfor 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: Any = <snakeoil.klass.properties.kls object>, 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_attrfor documentation of the misc params.
- snakeoil.klass.jit_attr_none(func: ~typing.Callable[[~typing.Any], ~snakeoil.klass.properties.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.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
chained_getter
- 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.
- param target:
class or function to steal docs from
- param 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
- param 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__