Convenience facilities for objects.
*Latest release 20241009*:
public_subclasses: catch TypeError from "type.__subclasses__", which is just a function.
## <a name="as_dict"></a>`as_dict(o, selector=None)`
Return a dictionary with keys mapping to the values of the attributes of `o`.
Parameters:
* `o`: the object to map
* `selector`: the optional selection criterion
If `selector` is omitted or `None`, select "public" attributes,
those not commencing with an underscore.
If `selector` is a `str`, select attributes starting with `selector`.
Otherwise presume `selector` is callable
and select attributes `attr` where `selector(attr)` is true.
## <a name="copy"></a>`copy(obj, *a, **kw)`
Convenient function to shallow copy an object with simple modifications.
Performs a shallow copy of `self` using copy.copy.
Treat all positional parameters as attribute names, and
replace those attributes with shallow copies of the original
attribute.
Treat all keyword arguments as (attribute,value) tuples and
replace those attributes with the supplied values.
## <a name="flavour"></a>`flavour(obj)`
Return constants indicating the ``flavour'' of an object:
* `T_MAP`: DictType, DictionaryType, objects with an __keys__ or keys attribute.
* `T_SEQ`: TupleType, ListType, objects with an __iter__ attribute.
* `T_SCALAR`: Anything else.
## <a name="O"></a>Class `O(types.SimpleNamespace)`
The `O` class is now obsolete, please subclass `types.SimpleNamespace`
or use a dataclass.
## <a name="O_attritems"></a>`O_attritems(o)`
Generator yielding `(attr,value)` for relevant attributes of `o`.
## <a name="O_attrs"></a>`O_attrs(o)`
Yield attribute names from `o` which are pertinent to `O_str`.
Note: this calls `getattr(o,attr)` to inspect it in order to
prune callables.
## <a name="O_merge"></a>`O_merge(o, _conflict=None, _overwrite=False, **kw)`
Merge key:value pairs from a mapping into an object.
Ignore keys that do not start with a letter.
New attributes or attributes whose values compare equal are
merged in. Unequal values are passed to:
_conflict(o, attr, old_value, new_value)
to resolve the conflict. If _conflict is omitted or None
then the new value overwrites the old if _overwrite is true.
## <a name="O_str"></a>`O_str(o, no_recurse=False, seen=None)`
Return a `str` representation of the object `o`.
Parameters:
* `o`: the object to describe.
* `no_recurse`: if true, do not recurse into the object's structure.
Default: `False`.
* `seen`: a set of previously sighted objects
to prevent recursion loops.
## <a name="obj_as_dict"></a>`obj_as_dict(o, **kw)`
OBSOLETE obj_as_dict
OBSOLETE convesion of an object to a `dict`. Please us `cs.obj.as_dict`.
## <a name="Proxy"></a>Class `Proxy`
An extremely simple proxy object
that passes all unmatched attribute accesses to the proxied object.
Note that setattr and delattr work directly on the proxy, not the proxied object.
## <a name="public_subclasses"></a>`public_subclasses(cls)`
Return a list of the subclasses of `cls` which has public names.
## <a name="Sentinel"></a>Class `Sentinel`
A simple class for named sentinels whose `str()` is just the name
and whose `==` uses `is`.
Example:
>>> from cs.obj import Sentinel
>>> MISSING = Sentinel("MISSING")
>>> print(MISSING)
MISSING
>>> other = Sentinel("other")
>>> MISSING == other
False
>>> MISSING == MISSING
True
## <a name="singleton"></a>`singleton(registry, key, factory, fargs, fkwargs)`
Obtain an object for `key` via `registry` (a mapping of `key`=>object).
Return `(is_new,object)`.
If the `key` exists in the registry, return the associated object.
Otherwise create a new object by calling `factory(*fargs,**fkwargs)`
and store it as `key` in the `registry`.
The `registry` may be any mapping of `key`s to objects
but will usually be a `weakref.WeakValueDictionary`
in order that object references expire as normal,
allowing garbage collection.
*Note*: this function *is not* thread safe.
Multithreaded users should hold a mutex.
See the `SingletonMixin` class for a simple mixin to create
singleton classes,
which does provide thread safe operations.
## <a name="SingletonMixin"></a>Class `SingletonMixin`
A mixin turning a subclass into a singleton factory.
*Note*: this mixin overrides `object.__new__`
and may not play well with other classes which override `__new__`.
*Warning*: because of the mechanics of `__new__`,
the instance's `__init__` method will always be called
after `__new__`,
even when a preexisting object is returned.
Therefore that method should be sensible
even for an already initialised
and probably subsequently modified object.
My suggested approach is to access some attribute,
and preemptively return if it already exists.
Example:
def __init__(self, x, y):
if 'x' in self.__dict__:
return
self.x = x
self.y = y
*Note*: we probe `self.__dict__` above to accomodate classes
with a `__getattr__` method.
*Note*: each class registry has a lock,
which ensures that reuse of an object
in multiple threads will call the `__init__` method
in a thread safe serialised fashion.
Implementation requirements:
a subclass should:
* provide a method `_singleton_key(*args,**kwargs)`
returning a key for use in the single registry,
computed from the positional and keyword arguments
supplied on instance creation
i.e. those which `__init__` would normally receive.
This should have the same signature as `__init__`
but using `cls` instead of `self`.
* provide a normal `__init__` method
which can be safely called again
after some earlier initialisation.
This class is thread safe for the registry operations.
Example:
class Pool(SingletonMixin):
@classmethod
def _singleton_key(cls, foo, bah=3):
return foo, bah
def __init__(self, foo, bah=3):
if hasattr(self, 'foo'):
return
... normal __init__ stuff here ...
self.foo = foo
...
*`SingletonMixin.__hash__(self)`*:
default hash and equality methods
*`SingletonMixin.singleton_also_by(also_key, key)`*:
Obtain a singleton by a secondary key.
Return the instance or `None`.
Parameters:
* `also_key`: the name of the secondary key index
* `key`: the key for the index
## <a name="TrackedClassMixin"></a>Class `TrackedClassMixin`
A mixin to track all instances of a particular class.
This is aimed at checking the global state of objects of a
particular type, particularly states like counters. The
tracking is attached to the class itself.
The class to be tracked includes this mixin as a superclass and calls:
TrackedClassMixin.__init__(class_to_track)
from its __init__ method. Note that `class_to_track` is
typically the class name itself, not `type(self)` which would
track the specific subclass. At some relevant point one can call:
self.tcm_dump(class_to_track[, file])
`class_to_track` needs a `tcm_get_state` method to return the
salient information, such as this from cs.resources.MultiOpenMixin:
def tcm_get_state(self):
return {'opened': self.opened, 'opens': self._opens}
See cs.resources.MultiOpenMixin for example use.
*`TrackedClassMixin.tcm_all_state(klass)`*:
Generator yielding tracking information
for objects of type `klass`
in the form `(o,state)`
where `o` if a tracked object
and `state` is the object's `get_tcm_state` method result.
*`TrackedClassMixin.tcm_dump(klass, f=None)`*:
Dump the tracking information for `klass` to the file `f`
(default `sys.stderr`).
# Release Log
*Release 20241009*:
public_subclasses: catch TypeError from "type.__subclasses__", which is just a function.
*Release 20241005*:
New public_subclasses(cls) returning all subclasses with public names.
*Release 20220918*:
* SingletonMixin: change example to probe self__dict__ instead of hasattr, faster and less fragile.
* New Sentinel class for named sentinel objects, equal only to their own instance.
*Release 20220530*:
SingletonMixin: add default __hash__ and __eq__ methods to support dict and set membership.
*Release 20210717*:
SingletonMixin: if cls._singleton_key returns None we always make a new instance and do not register it.
*Release 20210306*:
SingletonMixin: make singleton_also_by() a public method.
*Release 20210131*:
SingletonMixin: new _singleton_also_indexmap method to return a mapping of secondary keys to values to secondary lookup, _singleton_also_index() to update these indices, _singleton_also_by to look up a secondary index.
*Release 20210122*:
SingletonMixin: new _singleton_instances() method returning a list of the current instances.
*Release 20201227*:
SingletonMixin: correctly invoke __new__, a surprisingly fiddly task to get right.
*Release 20201021*:
* @OBSOLETE(obj_as_dict), recommend "as_dict()".
* [BREAKING] change as_dict() to accept a single optional selector instead of various mutually exclusive keywords.
*Release 20200716*:
SingletonMixin: no longer require special _singleton_init method, reuse default __init__ implicitly through __new__ mechanics.
*Release 20200517*:
Documentation improvements.
*Release 20200318*:
* Replace obsolete O class with a new subclass of SimpleNamespace which issues a warning.
* New singleton() generic factory function and SingletonMixin mixin class for making singleton classes.
*Release 20190103*:
* New mixin class TrackedClassMixin to track all instances of a particular class.
* Documentation updates.
*Release 20170904*:
Minor cleanups.
*Release 20160828*:
* Use "install_requires" instead of "requires" in DISTINFO.
* Minor tweaks.
*Release 20150118*:
move long_description into cs/README-obj.rst
*Release 20150110*:
cleaned out some old junk, readied metadata for PyPI
Raw data
{
"_id": null,
"home_page": null,
"name": "cs.obj",
"maintainer": null,
"docs_url": null,
"requires_python": null,
"maintainer_email": null,
"keywords": "python2, python3",
"author": null,
"author_email": "Cameron Simpson <cs@cskk.id.au>",
"download_url": "https://files.pythonhosted.org/packages/f1/be/f324fa8e013f998631c02fafc66f75c237b0910fa8c861076523cbb1217b/cs_obj-20241009.tar.gz",
"platform": null,
"description": "Convenience facilities for objects.\n\n*Latest release 20241009*:\npublic_subclasses: catch TypeError from \"type.__subclasses__\", which is just a function.\n\n## <a name=\"as_dict\"></a>`as_dict(o, selector=None)`\n\nReturn a dictionary with keys mapping to the values of the attributes of `o`.\n\nParameters:\n* `o`: the object to map\n* `selector`: the optional selection criterion\n\nIf `selector` is omitted or `None`, select \"public\" attributes,\nthose not commencing with an underscore.\n\nIf `selector` is a `str`, select attributes starting with `selector`.\n\nOtherwise presume `selector` is callable\nand select attributes `attr` where `selector(attr)` is true.\n\n## <a name=\"copy\"></a>`copy(obj, *a, **kw)`\n\nConvenient function to shallow copy an object with simple modifications.\n\nPerforms a shallow copy of `self` using copy.copy.\n\nTreat all positional parameters as attribute names, and\nreplace those attributes with shallow copies of the original\nattribute.\n\nTreat all keyword arguments as (attribute,value) tuples and\nreplace those attributes with the supplied values.\n\n## <a name=\"flavour\"></a>`flavour(obj)`\n\nReturn constants indicating the ``flavour'' of an object:\n* `T_MAP`: DictType, DictionaryType, objects with an __keys__ or keys attribute.\n* `T_SEQ`: TupleType, ListType, objects with an __iter__ attribute.\n* `T_SCALAR`: Anything else.\n\n## <a name=\"O\"></a>Class `O(types.SimpleNamespace)`\n\nThe `O` class is now obsolete, please subclass `types.SimpleNamespace`\nor use a dataclass.\n\n## <a name=\"O_attritems\"></a>`O_attritems(o)`\n\nGenerator yielding `(attr,value)` for relevant attributes of `o`.\n\n## <a name=\"O_attrs\"></a>`O_attrs(o)`\n\nYield attribute names from `o` which are pertinent to `O_str`.\n\nNote: this calls `getattr(o,attr)` to inspect it in order to\nprune callables.\n\n## <a name=\"O_merge\"></a>`O_merge(o, _conflict=None, _overwrite=False, **kw)`\n\nMerge key:value pairs from a mapping into an object.\n\nIgnore keys that do not start with a letter.\nNew attributes or attributes whose values compare equal are\nmerged in. Unequal values are passed to:\n\n _conflict(o, attr, old_value, new_value)\n\nto resolve the conflict. If _conflict is omitted or None\nthen the new value overwrites the old if _overwrite is true.\n\n## <a name=\"O_str\"></a>`O_str(o, no_recurse=False, seen=None)`\n\nReturn a `str` representation of the object `o`.\n\nParameters:\n* `o`: the object to describe.\n* `no_recurse`: if true, do not recurse into the object's structure.\n Default: `False`.\n* `seen`: a set of previously sighted objects\n to prevent recursion loops.\n\n## <a name=\"obj_as_dict\"></a>`obj_as_dict(o, **kw)`\n\nOBSOLETE obj_as_dict\n\nOBSOLETE convesion of an object to a `dict`. Please us `cs.obj.as_dict`.\n\n## <a name=\"Proxy\"></a>Class `Proxy`\n\nAn extremely simple proxy object\nthat passes all unmatched attribute accesses to the proxied object.\n\nNote that setattr and delattr work directly on the proxy, not the proxied object.\n\n## <a name=\"public_subclasses\"></a>`public_subclasses(cls)`\n\nReturn a list of the subclasses of `cls` which has public names.\n\n## <a name=\"Sentinel\"></a>Class `Sentinel`\n\nA simple class for named sentinels whose `str()` is just the name\nand whose `==` uses `is`.\n\nExample:\n\n >>> from cs.obj import Sentinel\n >>> MISSING = Sentinel(\"MISSING\")\n >>> print(MISSING)\n MISSING\n >>> other = Sentinel(\"other\")\n >>> MISSING == other\n False\n >>> MISSING == MISSING\n True\n\n## <a name=\"singleton\"></a>`singleton(registry, key, factory, fargs, fkwargs)`\n\nObtain an object for `key` via `registry` (a mapping of `key`=>object).\nReturn `(is_new,object)`.\n\nIf the `key` exists in the registry, return the associated object.\nOtherwise create a new object by calling `factory(*fargs,**fkwargs)`\nand store it as `key` in the `registry`.\n\nThe `registry` may be any mapping of `key`s to objects\nbut will usually be a `weakref.WeakValueDictionary`\nin order that object references expire as normal,\nallowing garbage collection.\n\n*Note*: this function *is not* thread safe.\nMultithreaded users should hold a mutex.\n\nSee the `SingletonMixin` class for a simple mixin to create\nsingleton classes,\nwhich does provide thread safe operations.\n\n## <a name=\"SingletonMixin\"></a>Class `SingletonMixin`\n\nA mixin turning a subclass into a singleton factory.\n\n*Note*: this mixin overrides `object.__new__`\nand may not play well with other classes which override `__new__`.\n\n*Warning*: because of the mechanics of `__new__`,\nthe instance's `__init__` method will always be called\nafter `__new__`,\neven when a preexisting object is returned.\nTherefore that method should be sensible\neven for an already initialised\nand probably subsequently modified object.\n\nMy suggested approach is to access some attribute,\nand preemptively return if it already exists.\nExample:\n\n def __init__(self, x, y):\n if 'x' in self.__dict__:\n return\n self.x = x\n self.y = y\n\n*Note*: we probe `self.__dict__` above to accomodate classes\nwith a `__getattr__` method.\n\n*Note*: each class registry has a lock,\nwhich ensures that reuse of an object\nin multiple threads will call the `__init__` method\nin a thread safe serialised fashion.\n\nImplementation requirements:\na subclass should:\n* provide a method `_singleton_key(*args,**kwargs)`\n returning a key for use in the single registry,\n computed from the positional and keyword arguments\n supplied on instance creation\n i.e. those which `__init__` would normally receive.\n This should have the same signature as `__init__`\n but using `cls` instead of `self`.\n* provide a normal `__init__` method\n which can be safely called again\n after some earlier initialisation.\n\nThis class is thread safe for the registry operations.\n\nExample:\n\n class Pool(SingletonMixin):\n\n @classmethod\n def _singleton_key(cls, foo, bah=3):\n return foo, bah\n\n def __init__(self, foo, bah=3):\n if hasattr(self, 'foo'):\n return\n ... normal __init__ stuff here ...\n self.foo = foo\n ...\n\n*`SingletonMixin.__hash__(self)`*:\ndefault hash and equality methods\n\n*`SingletonMixin.singleton_also_by(also_key, key)`*:\nObtain a singleton by a secondary key.\nReturn the instance or `None`.\n\nParameters:\n* `also_key`: the name of the secondary key index\n* `key`: the key for the index\n\n## <a name=\"TrackedClassMixin\"></a>Class `TrackedClassMixin`\n\nA mixin to track all instances of a particular class.\n\nThis is aimed at checking the global state of objects of a\nparticular type, particularly states like counters. The\ntracking is attached to the class itself.\n\nThe class to be tracked includes this mixin as a superclass and calls:\n\n TrackedClassMixin.__init__(class_to_track)\n\nfrom its __init__ method. Note that `class_to_track` is\ntypically the class name itself, not `type(self)` which would\ntrack the specific subclass. At some relevant point one can call:\n\n self.tcm_dump(class_to_track[, file])\n\n`class_to_track` needs a `tcm_get_state` method to return the\nsalient information, such as this from cs.resources.MultiOpenMixin:\n\n def tcm_get_state(self):\n return {'opened': self.opened, 'opens': self._opens}\n\nSee cs.resources.MultiOpenMixin for example use.\n\n*`TrackedClassMixin.tcm_all_state(klass)`*:\nGenerator yielding tracking information\nfor objects of type `klass`\nin the form `(o,state)`\nwhere `o` if a tracked object\nand `state` is the object's `get_tcm_state` method result.\n\n*`TrackedClassMixin.tcm_dump(klass, f=None)`*:\nDump the tracking information for `klass` to the file `f`\n(default `sys.stderr`).\n\n# Release Log\n\n\n\n*Release 20241009*:\npublic_subclasses: catch TypeError from \"type.__subclasses__\", which is just a function.\n\n*Release 20241005*:\nNew public_subclasses(cls) returning all subclasses with public names.\n\n*Release 20220918*:\n* SingletonMixin: change example to probe self__dict__ instead of hasattr, faster and less fragile.\n* New Sentinel class for named sentinel objects, equal only to their own instance.\n\n*Release 20220530*:\nSingletonMixin: add default __hash__ and __eq__ methods to support dict and set membership.\n\n*Release 20210717*:\nSingletonMixin: if cls._singleton_key returns None we always make a new instance and do not register it.\n\n*Release 20210306*:\nSingletonMixin: make singleton_also_by() a public method.\n\n*Release 20210131*:\nSingletonMixin: new _singleton_also_indexmap method to return a mapping of secondary keys to values to secondary lookup, _singleton_also_index() to update these indices, _singleton_also_by to look up a secondary index.\n\n*Release 20210122*:\nSingletonMixin: new _singleton_instances() method returning a list of the current instances.\n\n*Release 20201227*:\nSingletonMixin: correctly invoke __new__, a surprisingly fiddly task to get right.\n\n*Release 20201021*:\n* @OBSOLETE(obj_as_dict), recommend \"as_dict()\".\n* [BREAKING] change as_dict() to accept a single optional selector instead of various mutually exclusive keywords.\n\n*Release 20200716*:\nSingletonMixin: no longer require special _singleton_init method, reuse default __init__ implicitly through __new__ mechanics.\n\n*Release 20200517*:\nDocumentation improvements.\n\n*Release 20200318*:\n* Replace obsolete O class with a new subclass of SimpleNamespace which issues a warning.\n* New singleton() generic factory function and SingletonMixin mixin class for making singleton classes.\n\n*Release 20190103*:\n* New mixin class TrackedClassMixin to track all instances of a particular class.\n* Documentation updates.\n\n*Release 20170904*:\nMinor cleanups.\n\n*Release 20160828*:\n* Use \"install_requires\" instead of \"requires\" in DISTINFO.\n* Minor tweaks.\n\n*Release 20150118*:\nmove long_description into cs/README-obj.rst\n\n*Release 20150110*:\ncleaned out some old junk, readied metadata for PyPI\n",
"bugtrack_url": null,
"license": "GNU General Public License v3 or later (GPLv3+)",
"summary": "Convenience facilities for objects.",
"version": "20241009",
"project_urls": {
"MonoRepo Commits": "https://bitbucket.org/cameron_simpson/css/commits/branch/main",
"Monorepo Git Mirror": "https://github.com/cameron-simpson/css",
"Monorepo Hg/Mercurial Mirror": "https://hg.sr.ht/~cameron-simpson/css",
"Source": "https://github.com/cameron-simpson/css/blob/main/lib/python/cs/obj.py"
},
"split_keywords": [
"python2",
" python3"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "46754bbdbddc7ff472246a712577593c60cf72be42a56196dd096054d4b7d35e",
"md5": "a96654e0b5342e9f01797dcfecbc182b",
"sha256": "d77d4e51be3103d1d1344bf59112a6873dafaec7bb7e730d6291f1981e2c15c8"
},
"downloads": -1,
"filename": "cs.obj-20241009-py3-none-any.whl",
"has_sig": false,
"md5_digest": "a96654e0b5342e9f01797dcfecbc182b",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": null,
"size": 10896,
"upload_time": "2024-10-09T05:34:57",
"upload_time_iso_8601": "2024-10-09T05:34:57.366332Z",
"url": "https://files.pythonhosted.org/packages/46/75/4bbdbddc7ff472246a712577593c60cf72be42a56196dd096054d4b7d35e/cs.obj-20241009-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "f1bef324fa8e013f998631c02fafc66f75c237b0910fa8c861076523cbb1217b",
"md5": "4fd1cb9c5c1fc3a8318e2c6b94686198",
"sha256": "ebcd303902593f239c2935d48313fb3a7e53daad94f0032c6525f078479cf7ef"
},
"downloads": -1,
"filename": "cs_obj-20241009.tar.gz",
"has_sig": false,
"md5_digest": "4fd1cb9c5c1fc3a8318e2c6b94686198",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 11244,
"upload_time": "2024-10-09T05:34:59",
"upload_time_iso_8601": "2024-10-09T05:34:59.474060Z",
"url": "https://files.pythonhosted.org/packages/f1/be/f324fa8e013f998631c02fafc66f75c237b0910fa8c861076523cbb1217b/cs_obj-20241009.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-10-09 05:34:59",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "cameron-simpson",
"github_project": "css",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "cs.obj"
}