copy_class

privex.helpers.collections.copy_class(obj: Type[T], name=None, deep_copy=True, deep_private=False, **kwargs) → Union[Type[T], type][source]

Attempts to create a full copy of a type or class, severing most object pointers such as attributes containing a dict / list, along with classes or instances of classes.

Example:

>>> class SomeClass:
>>>     example = 'lorem ipsum'
>>>     data = ['hello', 'world']
>>>     testing = 123
>>>
>>> from privex.helpers import copy_class
>>> OtherClass = copy_class(SomeClass, name='OtherClass')

If you then append to the list attribute data on both SomeClass and OtherClass - with a different item appended to each class, you’ll see that the added item was only added to data for that class, and not to the other class, proving the original and the copy are independent from each other:

>>> SomeClass.data.append('lorem')
>>> OtherClass.data.append('ipsum')
>>> SomeClass.data
['hello', 'world', 'lorem']
>>> OtherClass.data
['hello', 'world', 'ipsum']
Parameters
  • obj (Type[T]) – A type / class to attempt to duplicate, deep copying each individual object in the class, to avoid any object pointers shared between the original and the copy.

  • name (str|None) – The class name to use for the copy of obj. If not specified, defaults to the original class name from obj

  • deep_copy (bool) – (Default: True) If True, uses copy.deepcopy() to deep copy each attribute in obj to the copy. If False, then standard references will be used, which may result in object pointers being copied.

  • deep_private (bool) – (Default: False) If True, copy.deepcopy() will be used on “private” class attributes, i.e. ones that start with __. If False, attributes starting with __ will not be deep copied, only a standard assignment/reference will be used.

  • kwargs – Additional advanced settings (see keyword pydoc entries for this function)

  • use_bases (bool) – (Default: True) If True, copy the inheritance (bases) from obj into the class copy.

  • quiet (bool) – (Default False) If True, log deep copy errors as debug level (usually silent in production apps) instead of the louder warning.

  • bases (tuple) – A tuple of classes to use as “bases” (inheritance) for the class copy. If not specified, copies __bases__ from the original class.

  • module (str) – If specified, overrides the module __module__ in the class copy with this string, instead of copying from the original class.

Return Type[T] obj_copy

A deep copy of the original obj