qnet.utils.singleton module

Constant algebraic objects are best implemented as singletons (i.e., they only exist as a single object). This module provides the means to declare singletons:

  • The Singleton metaclass ensures that every class based on it produces the same object every time it is instantiated
  • The singleton_object() class decorator converts a singleton class definition into the actual singleton object

Singletons in QNET should use both of these.

Note

In order for the Sphinx autodoc extension to correctly recognize singletons, a custom documenter will have to be registered. The Sphinx conf.py file must contain the following:

from sphinx.ext.autodoc import DataDocumenter

class SingletonDocumenter(DataDocumenter):
    directivetype = 'data'
    objtype = 'singleton'
    priority = 20

    @classmethod
    def can_document_member(cls, member, membername, isattr, parent):
        return isinstance(member, qnet.utils.singleton.SingletonType)

def setup(app):
    # ... (other hook settings)
    app.add_autodocumenter(SingletonDocumenter)

Summary

Classes:

Singleton Metaclass for singletons

Functions:

singleton_object Class decorator that transforms (and replaces) a class definition (which must have a Singleton metaclass) with the actual singleton object.

Data:

SingletonType A dummy type that may be used to check whether an object is a Singleton.

__all__: Singleton, SingletonType, singleton_object

Reference

qnet.utils.singleton.singleton_object(cls)[source]

Class decorator that transforms (and replaces) a class definition (which must have a Singleton metaclass) with the actual singleton object. Ensures that the resulting object can still be “instantiated” (i.e., called), returning the same object. Also ensures the object can be pickled, is hashable, and has the correct string representation (the name of the singleton)

If the class defines a _hash_val class attribute, the hash of the singleton will be the hash of that value, and the singleton will compare equal to that value. Otherwise, the singleton will have a unique hash and compare equal only to itself.

class qnet.utils.singleton.Singleton[source]

Bases: abc.ABCMeta

Metaclass for singletons

Any instantiation of a singleton class yields the exact same object, e.g.:

>>> class MyClass(metaclass=Singleton):
...     pass
>>> a = MyClass()
>>> b = MyClass()
>>> a is b
True

You can check that an object is a singleton using:

>>> isinstance(a, SingletonType)
True
qnet.utils.singleton.SingletonType = <class 'qnet.utils.singleton.SingletonType'>[source]

A dummy type that may be used to check whether an object is a Singleton:

isinstance(obj, SingletonType)