hbutils.model.clazz

Overview:

Useful functions for building class models. This module provides decorators and utilities for enhancing Python classes with features like automatic field access, visual representation, constructor generation, hash/equality operations, and property accessors.

get_field

hbutils.model.clazz.get_field(obj, name: str, default=<SingletonMark 'no_default_value'>)[source]

Get field from object. Private field is supported.

Parameters:
  • obj (object) – The given object.

  • name (str) – Field to be got.

  • default – Default value when failed. Defaults to _NO_DEFAULT_VALUE.

Returns:

Field value of the field.

Raises:

AttributeError – If the field does not exist and no default is provided.

Example::
>>> class MyClass:
...     def __init__(self):
...         self.__private_field = 42
>>> obj = MyClass()
>>> get_field(obj, '__private_field')
42
>>> get_field(obj, 'nonexistent', default='default_value')
'default_value'

asitems

hbutils.model.clazz.asitems(items: Iterable[str])[source]

Define fields in the class level.

Parameters:

items (Iterable[str]) – Field name items.

Returns:

Decorator to decorate the given class.

Return type:

Callable

Example::
>>> @visual()
>>> @constructor(doc='''
...     Overview:
...         This is the constructor of class :class:`T`.
... ''')
>>> @asitems(['x', 'y'])
>>> class T:
...     @property
...     def x(self):
...         return self.__first
...
...     @property
...     def y(self):
...         return self.__second

Note

This decorator sets the __items__ attribute on the class, which is used by other decorators to determine which fields to process.

visual

hbutils.model.clazz.visual(items: Iterable | None = None, show_id: bool = False)[source]

Decorate class to be visible by repr.

Parameters:
  • items (Optional[Iterable]) – Items to be displayed. Default is None, which means automatically find the private fields and display them.

  • show_id (bool) – Show hex id in representation string or not. Defaults to False.

Returns:

Decorator to decorate the given class.

Return type:

Callable

Example::
>>> @visual()
>>> class T:
...     def __init__(self, x, y):
...         self.__first = x
...         self.__second = y
>>> repr(T(1, 2))
'<T first: 1, second: 2>'
>>> @visual(show_id=True)
>>> class T2:
...     def __init__(self, x):
...         self.__x = x
>>> repr(T2(42))
'<T2 0x... x: 42>'

Note

This decorator automatically generates a __repr__ method for the class that displays the specified fields or all private fields if none are specified.

constructor

hbutils.model.clazz.constructor(params: Iterable | None = None, doc: str | None = None)[source]

Decorate class to create an init function.

Parameters:
  • params (Optional[Iterable]) – Parameters of constructor, should be an iterator of items, each item should be a single string or a tuple of string and default value. Default is None, which means no arguments.

  • doc (Optional[str]) – Documentation of constructor function. Defaults to None.

Returns:

Decorator to decorate the given class.

Return type:

Callable

Example::
>>> @constructor(['x', ('y', 2)], '''
...     Overview:
...         This is the constructor of class :class:`T`.
... ''')
>>> class T:
...     # the same as:
...     # def __init__(self, x, y=2):
...     #     self.__x = x
...     #     self.__y = y
...
...     @property
...     def x(self):
...         return self.__x
...
...     @property
...     def y(self):
...         return self.__y
>>> t = T(1)
>>> t.x, t.y
(1, 2)

Note

This decorator automatically generates an __init__ method for the class that initializes the specified fields with the provided parameters.

hasheq

hbutils.model.clazz.hasheq(items: Iterable | None = None)[source]

Decorate class to support hashing and equality comparison.

Parameters:

items (Optional[Iterable]) – Items to be hashed and compared. Default is None, which means automatically find the private fields and use them.

Returns:

Decorator to decorate the given class.

Return type:

Callable

Example::
>>> @hasheq(['x', 'y'])
>>> class T:
...     def __init__(self, x, y):
...         self.__first = x
...         self.__second = y
>>> t1 = T(1, 2)
>>> t2 = T(1, 2)
>>> t1 == t2
True
>>> hash(t1) == hash(t2)
True

Using with asitems():

>>> @hasheq()
>>> @constructor()
>>> @asitems(['x', 'y'])
>>> class T1:

… pass >>> t1 = T1(1, 2) >>> t2 = T1(1, 2) >>> t1 == t2 True

Note

This decorator generates __hash__, __eq__, and __ne__ methods for the class based on the specified fields. Objects are considered equal if they are of the same class and all specified field values are equal.

accessor

hbutils.model.clazz.accessor(items: Iterable | None = None, readonly: bool = False)[source]

Decorate class to be accessible by property accessors.

Parameters:
  • items (Optional[Iterable]) – Items to be accessed. Default is None, which means automatically find the private fields and create accessors for them.

  • readonly (bool) – Default readonly or not. Default is False, which means make the accessor be writable when rw option is not given.

Returns:

Decorator to decorate the given class.

Return type:

Callable

Example::
>>> @accessor(readonly=True)
>>> @asitems(['x', 'y'])
>>> class T:
...     def __init__(self, x, y):
...         self.__x = x
...         self.__y = y
>>> t = T(2, 100)
>>> t.x  # 2
2
>>> t.y  # 100
100

With writable access:

>>> @accessor(readonly=False)
>>> @asitems(['x', 'y'])
>>> class T2:
...     def __init__(self, x, y):
...         self.__x = x
...         self.__y = y
>>> t = T2(2, 100)
>>> t.x = 42
>>> t.x
42

With mixed access control:

>>> @accessor([('x', 'ro'), ('y', 'rw')])
>>> class T3:
...     def __init__(self, x, y):
...         self.__x = x
...         self.__y = y
>>> t = T3(1, 2)
>>> t.y = 42  # OK
>>> # t.x = 10  # This would raise AttributeError

Note

This decorator automatically generates property accessors for the specified fields. Each item can be either a string (field name) or a tuple of (field name, access mode). Access modes: ‘r’/’ro’/’readonly’ for read-only, ‘w’/’rw’/’writable’ for read-write.