base classes (quanguru.classes.base
)#
Contains two main base classes (for naming and sub/superSys) and their helper classes, functions, decorators.
|
Implements a name attribute and a naming standard. |
|
Implements the sub/super-system attributes, auxiliary object and dictionary, and copy method. |
|
aliasClass is introduced for the naming functionality of the qObjects. |
|
Method to find a key or any other obj equal to the key in a |
Extending the dictionary class to treat the keys satisfying |
an auxiliary class used to instantiate a dummy object for the |
|
|
a decorator to call the decorated method recursively for every element of a list/tuple input (and possibly exclude certain objects). |
|
A recursive decorator for methods like addSubSys which add items into dictionaries (eg. |
Function Name |
Docstrings |
Unit Tests |
Tutorials |
---|---|---|---|
named |
✅ |
✅ |
✅ |
qBase |
✅ |
✅ |
❌ |
aliasClass |
✅ |
✅ |
✅ |
keySearch |
✅ |
✅ |
✅ |
aliasDict |
✅ |
✅ |
✅ |
_auxiliaryClass |
✅ |
❌ |
❌ |
_recurseIfList |
✅ |
❌ |
❌ |
addDecorator |
✅ |
❌ |
❌ |
- _recurseIfList(func: Callable) Callable [source]#
a decorator to call the decorated method recursively for every element of a list/tuple input (and possibly exclude certain objects). It is used in various places of the library (exclude is useful/used in some of them to avoid infinite recursive calls).
- class aliasClass(name: typing.Optional[str] = None, alias: typing.List[typing.Any] = <class 'list'>)[source]#
Bases:
object
aliasClass is introduced for the naming functionality of the qObjects. It is created to be used as the name attribute of qObjects and to work with the extended dictionary
aliasDict
. The default name of qObjects is assigned to be__name
attribute, and the user assigned aliases for a qObject are stored in the__alias
list. The string representation and hash value of an aliasClass objects is obtained from its name.- __name: Optional[str]#
Protected name attribute of an aliasClass object, set&get through the
name
property. Default isNone
. It can be set to any string (which cannot be changed later, unless directly overwrittingself._aliasClass__name
).
- property name: Optional[str]#
Getter of the name property, returns
self.__name
.Setter of the name property, sets
self.__name
to givenname
provided that theself.__name is None
and the givenname
is a string. This means that the name can only be a string and cannot be changed once set. Unless, of course, directly overwriting the protected attribute.- Raises
TypeError – Raised if given name is not string
- property alias: List#
Getter of the alias property, returns the alias list.
Setter of the alias property, adds a new alias for the aliasClass object (if the given alias is not already in the list).
- __members() Tuple #
- Returns
a tuple containing the name and all aliases
- _allStringSum() str [source]#
Adds and returns all the strings in members.
This is currently used with the saveCSV method to add this string to file name
- __eq__(other: Union[quanguru.classes.base.aliasClass, str]) bool [source]#
Equality of any two aliasClass objects (or an aliasClass object to a string) is determined by comparing their names and all their aliases (or to given string), if at least one of them are the same (or the same as the given string), aliasClass objects (or the aliasClass object and the given string) are considereed to be equal.
- Parameters
other (Union[aliasClass, str]) – aliasClass object or string to check the equality with self
- keySearch(obj: Dict, k: Any) Hashable [source]#
Method to find a key or any other obj equal to the key in a
dictionary.keys()
. This method is used inaliasDict
class (extendingdict
class) to find the actual key when usingaliasClass
as the key, which returns equal for a specific string (its name) or any other string in its list of aliases.- Parameters
obj (Dict) – The dictionary to search the key
k (Any) – The key to search in the dictionary (obj)
- Returns
the key, if the key itself or no equality is found in the dictionary keys. returns the equal key from the dictionary, if an equal key is found in the dictionary.
- class aliasDict[source]#
Bases:
dict
Extending the dictionary class to treat the keys satisfying
key1 == keys2
as the same key. This functionality is implemented to usealiasClass
objects as keys and to get the value by using the aliasClass object itself, its name, or any of its aliases as the key.NOTE no explicit tests for most of the extended methods, be careful in modifications.
- __getitem__(k: Hashable) Any [source]#
Gets the value from the dictionary for a given key or any of the keys that is equal to the given key. This enables to get a value using an
aliasClass
object itself, its name, or any any of it aliases.
- get(key: Hashable, default: Optional[Any] = None) Any [source]#
Modified get method to be compatible with extended
__getitem__()
method.
- __setitem__(k: Hashable, v: Any) None [source]#
Updates the value of a key in the dictionary, if the given key exists or any of the keys is equal to given key, otherwise creates an item (ie key:value pair) in the dictionary. This enables to set a value using an
aliasClass
object itself, its name, or any any of it aliases.
- __delitem__(k: Hashable) None [source]#
Deletes the item for a given key or any of the keys that is equal to the given key. This enables to delete a value using an
aliasClass
object itself, its name, or any any of it aliases.
- __contains__(o: Hashable) bool [source]#
Returns
True
if the key or any object equal to the key exists. This enables toreturn True
for analiasClass
object itself, its name, or any of it aliases.
- update(mapping: Optional[Mapping] = (), **kwargs) None [source]#
update method compatible with the extended get/set methods.
- setdefault(_aliasDict__key: Hashable, _aliasDict__default: Optional[Any] = None) Any [source]#
Modified setdefault method to be compatible with extended
__setitem__()
&__getitem__()
methods.
- copy() quanguru.classes.base.aliasDict [source]#
copy method to make sure the type is correct.
- class named(**kwargs)[source]#
Bases:
object
Implements a name attribute and a naming standard. It is inhereted by all the other qObjects so that they have unique default names, and users are able to assign aliases for any object. It uses the
aliasClass
for its name attribute to enable this.Default naming is
(_)class.label (same as class name) + number of instances created in a session
. The optional _ in the name is to distinguish between the objects created internally which is not trivially known by the user. The objects explicitly created by the user does not have an underscore in their names. There are 4 class attribute to achieve these, 1 the label and 3 for keeping number of (internal, external, and total number of) instances. One last counter is the total number of instances of the classes inherited from named.- label: str = 'named'#
(class attribute) class label used in default naming
- _internalInstances: int = 0#
(class attribute) number of instances created internally by the library
- _externalInstances: int = 0#
(class attribute) number of instances created explicitly by the user
- _instances: int = 0#
(class attribute) number of total instances = _internalInstances + _externalInstances
- _totalNumberOfInst: int = 0#
(class attribute) total number of instances including named and all the child classes
- _allInstacesDict = {}#
(class attribute) a weakValue dictionary to store a weakref to every instance. This is used to reach any instance by its name or alias using the
getByName
method _allInstacesDict = weakref.WeakValueDictionary() (could not pickle, so, for now, uses aliasDict which has problems with garbage collection in jupyter sessions)
- _internal: bool#
boolean to distinguish internally and explicitly created instances.
- __name: quanguru.classes.base.aliasClass#
protected name attribute is an instance of
named
class
- _allInstaces#
used in
getByNameOrAlias()
to properly pickle and reach updated objects during multi-processing
- getByNameOrAlias(name: Union[str, quanguru.classes.base.aliasClass]) quanguru.classes.base.named [source]#
Returns a reference for an object using its name or any alias.
Raises ValueError if it cannot find any object for the given name (or alias).
- _incrementInstances() None [source]#
Method used inside __init__ to increase internal/external and total number of instances.
- __namer() str #
Generates the default names.
- Returns
the default name
- property name: quanguru.classes.base.aliasClass#
Getter of the name property
returns __name
protected attribute. There is no setter, names are not allowed to be changed but can assign an alias.
- property alias: List#
alias property gets the list of aliases.
Sets (adds/extends into the list) alias (single/list of alias). Does not allow duplicate alias.
- classmethod clsInstances(_internal: Optional[bool] = None) int [source]#
This class method returns the number of instances:
Total number,
if _internal is None
internal,
if _internal is True
external,
if _internal is False
- classmethod _resetAll() None [source]#
Resets the counters and empties the weakref dictionary. Goal is to make this an equivalent to restarting a script or notebook.
- __setKwargs(**kwargs) None #
Method to set the attributes of the object from the given keywords and values. It is introduced to be used while instantiation of the object so that the protected attributes are set through the correspoding properties.
- Parameters
kwargs (Any) – Any attribute from the __slots__ (should take name-mangling into account, if used by a child class) or the name of corresponding property with an appropriate value type.
- class _auxiliaryClass[source]#
Bases:
object
an auxiliary class used to instantiate a dummy object for the
_auxiliaryObj
attribute.
- addDecorator(addFunction)[source]#
A recursive decorator for methods like addSubSys which add items into dictionaries (eg. subSys dictionary).
It is initially created to be used with
subSys
dictionary ofqBase
class, and the idea is to cover possible misuse ofadd
/create
subSys methods (while also creating flexibility).For example, if, instead of an instance, the class itself is given to
addSubSys
method, this decorator creates a new instance and includes the new instance to the dictionary. This also enables the flexible use ofaddSubSys
as replacement forcreateSubSys
.The wrapper is also decorated with the
_recurseIfList()
to make it recursive for list/tuple inputs.This decorator is also used for
_createParamBound
and_breakParamBound
methods for_paramBound
dictionary ofparamBoundBase
class.1. If the input (inp) is an instance of
named
, it calls the addFunction (the decorated method that does the actual adding) and its added into the relevant dictionary.Other input cases covered by this decorator are
If the input is a string, i.e. name/alias of an instance: finds the object from the
instNames
dict and calls the addFunction.If the input is a class, creates an instance of the class (has to be a child-class of
named
) and makes a recursive call (which will trigger 1).If the input is a list or tuple: makes a recursive call, which is handled by the
_recurseIfList`()
to iterate over every element of the given iterable, meaning anything in this list from 1. to 4. may be trigerred again depending on the value of the element in the iterable. (this can be combined with dict type to create nested dictionaries)raises an error if the object to be added is not an instance of
named
.
- class qBase(**kwargs)[source]#
Bases:
quanguru.classes.base.named
Implements the sub/super-system attributes, auxiliary object and dictionary, and copy method.
- label: str = 'qBase'#
(class attribute) class label used in default naming
- _internalInstances: int = 0#
(class attribute) number of instances created internally by the library
- _externalInstances: int = 0#
(class attribute) number of instances created explicitly by the user
- _instances: int = 0#
(class attribute) number of total instances = _internalInstances + _externalInstances
- _auxiliaryDict: Dict = {}#
(class attribute) aux dictionary to store auxiliary things as items to reach from any instance
- _auxiliaryObj: quanguru.classes.base._auxiliaryClass = <quanguru.classes.base._auxiliaryClass object>#
(class attribute) aux object to store auxiliary things as attributes to reach from any instance
- __superSys: Any#
protected attribute for super system property
- __subSys: Dict#
protected attribute for sub-system dictionary
- __auxDict#
attribute for the class attribute _auxiliary (this is required due to pickling in multi-processing)
- __auxObj#
attribute for the class attribute _auxiliaryObj (this is required due to pickling in multi-processing)
- property auxDict: Dict#
property to get and set auxiliary items into auxiliary dictionary. The setter updates the existing dictionary (instead of an single element into the existing dictionary) with a given one, ie. adds key:value pair for the non-existing keys and changes the value for existing keys.
- property auxObj: quanguru.classes.base._auxiliaryClass#
property to reach and set auxiliary attributes into auxiliary object
- property superSys: Any#
superSys property get/sets __superSys protected attribute
- property subSys: Dict#
subSys property gets the subSystem dictionary.
Setter resets the existing dictionary and adds the given object/s to
__subSys
dictionary. It calls theaddSubSys
, so it can used to add a single object, list/tuple of objects, by giving the name of the system, or giving class name to add a new instance of that class. Be aware that the setter resets the existing.
- addSubSys(subSys: quanguru.classes.base.named, **kwargs) quanguru.classes.base.named [source]#
Adds sub-system/s into subSys dictionary and works with instances, their name/alias, class themselves (creates an instance and adds), and list/tuple containing any combination of these.
- createSubSys(subSysClass: Any, **kwargs) quanguru.classes.base.named [source]#
Simply calls and returns the
addSubSys()
method, which is decorated to also cover creation.
- _removeSubSysExc(subSys: Any, _exclude=[]) None [source]#
Internal method that actually removes the sub-system, the removeSubSys is a wrapper around this function. This is introduced to avoid users interaction with _exclude, which needs to be empty for each removeSubSys call.
- removeSubSys(subSys: Any) None [source]#
Removes an object from the subSys dictionary and works with the object itself, its name, or any alias. Will raise regular keyError if the object is not in the dictionary, or typeError if the object is not an instance of named class.
- copy(**kwargs) quanguru.classes.base.qBase [source]#
Creates an empty copy of self. This method is introduced here to be extended in child class. In here, it ** does not copy ** the object, but creates a new object of the same class and sets the given kwargs