cs-obj 20241005__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cs/obj.py ADDED
@@ -0,0 +1,549 @@
1
+ #!/usr/bin/python
2
+ #
3
+ # Random stuff for "objects". - Cameron Simpson <cs@cskk.id.au>
4
+ #
5
+
6
+ r'''
7
+ Convenience facilities for objects.
8
+ '''
9
+
10
+ from __future__ import print_function
11
+ from collections import defaultdict
12
+ from copy import copy as copy0
13
+ import sys
14
+ import traceback
15
+ from types import SimpleNamespace
16
+ from threading import Lock
17
+ from weakref import WeakValueDictionary
18
+ from cs.deco import OBSOLETE
19
+ from cs.py3 import StringTypes
20
+
21
+ __version__ = '20241005'
22
+
23
+ DISTINFO = {
24
+ 'keywords': ["python2", "python3"],
25
+ 'classifiers': [
26
+ "Programming Language :: Python",
27
+ "Programming Language :: Python :: 2",
28
+ "Programming Language :: Python :: 3",
29
+ ],
30
+ 'install_requires': ['cs.deco', 'cs.py3'],
31
+ }
32
+
33
+ T_SEQ = 'SEQUENCE'
34
+ T_MAP = 'MAPPING'
35
+ T_SCALAR = 'SCALAR'
36
+
37
+ def flavour(obj):
38
+ """ Return constants indicating the ``flavour'' of an object:
39
+ * `T_MAP`: DictType, DictionaryType, objects with an __keys__ or keys attribute.
40
+ * `T_SEQ`: TupleType, ListType, objects with an __iter__ attribute.
41
+ * `T_SCALAR`: Anything else.
42
+ """
43
+ t = type(obj)
44
+ if isinstance(t, (tuple, list)):
45
+ return T_SEQ
46
+ if isinstance(t, dict):
47
+ return T_MAP
48
+ if hasattr(obj, '__keys__') or hasattr(obj, 'keys'):
49
+ return T_MAP
50
+ if hasattr(obj, '__iter__'):
51
+ return T_SEQ
52
+ return T_SCALAR
53
+
54
+ # pylint: disable=too-few-public-methods
55
+ class O(SimpleNamespace):
56
+ ''' The `O` class is now obsolete, please subclass `types.SimpleNamespace`
57
+ or use a dataclass.
58
+ '''
59
+
60
+ callers = set()
61
+
62
+ def __init__(self, **kw):
63
+ frame = traceback.extract_stack(None, 2)[0]
64
+ caller = (frame[0], frame[1])
65
+ if caller not in self.callers:
66
+ self.callers.add(caller)
67
+ print(
68
+ "WARNING: %s:%d %s: obsolete use of cs.obj.O, please shift to types.SimpleNamespace."
69
+ % (frame[0], frame[1], frame[2]),
70
+ file=sys.stderr
71
+ )
72
+ SimpleNamespace.__init__(self, **kw)
73
+
74
+ def O_merge(o, _conflict=None, _overwrite=False, **kw):
75
+ ''' Merge key:value pairs from a mapping into an object.
76
+
77
+ Ignore keys that do not start with a letter.
78
+ New attributes or attributes whose values compare equal are
79
+ merged in. Unequal values are passed to:
80
+
81
+ _conflict(o, attr, old_value, new_value)
82
+
83
+ to resolve the conflict. If _conflict is omitted or None
84
+ then the new value overwrites the old if _overwrite is true.
85
+ '''
86
+ for attr, value in kw.items():
87
+ if attr or not attr[0].isalpha():
88
+ continue
89
+ try:
90
+ ovalue = getattr(o, attr)
91
+ except AttributeError:
92
+ # new attribute -
93
+ setattr(o, attr, value)
94
+ else:
95
+ if ovalue != value:
96
+ if _conflict is None:
97
+ if _overwrite:
98
+ setattr(o, attr, value)
99
+ else:
100
+ _conflict(o, attr, ovalue, value)
101
+
102
+ def O_attrs(o):
103
+ ''' Yield attribute names from `o` which are pertinent to `O_str`.
104
+
105
+ Note: this calls `getattr(o,attr)` to inspect it in order to
106
+ prune callables.
107
+ '''
108
+ for attr in sorted(dir(o)):
109
+ if attr[0].isalpha():
110
+ try:
111
+ value = getattr(o, attr)
112
+ except AttributeError:
113
+ continue
114
+ if not callable(value):
115
+ yield attr
116
+
117
+ def O_attritems(o):
118
+ ''' Generator yielding `(attr,value)` for relevant attributes of `o`.
119
+ '''
120
+ for attr in O_attrs(o):
121
+ try:
122
+ value = getattr(o, attr)
123
+ except AttributeError:
124
+ continue
125
+ else:
126
+ yield attr, value
127
+
128
+ def O_str(o, no_recurse=False, seen=None):
129
+ ''' Return a `str` representation of the object `o`.
130
+
131
+ Parameters:
132
+ * `o`: the object to describe.
133
+ * `no_recurse`: if true, do not recurse into the object's structure.
134
+ Default: `False`.
135
+ * `seen`: a set of previously sighted objects
136
+ to prevent recursion loops.
137
+ '''
138
+ if seen is None:
139
+ seen = set()
140
+ obj_type = type(o)
141
+ if obj_type in StringTypes:
142
+ return repr(o)
143
+ if obj_type in (tuple, int, float, bool, list):
144
+ return str(o)
145
+ if obj_type is dict:
146
+ o2 = {k: str(v) for k, v in o.items()}
147
+ return str(o2)
148
+ if obj_type is set:
149
+ return 'set(%s)' % (','.join(sorted([str(item) for item in o])))
150
+ seen.add(id(o))
151
+ if no_recurse:
152
+ attrdesc_strs = [
153
+ "%s=<%s>" % (pattr, type(pvalue).__name__)
154
+ for pattr, pvalue in O_attritems(o)
155
+ ]
156
+ else:
157
+ attrdesc_strs = []
158
+ for pattr, pvalue in O_attritems(o):
159
+ if id(pvalue) in seen:
160
+ desc = "<%s>" % (type(pvalue).__name__,)
161
+ else:
162
+ desc = "%s=%s" % (
163
+ pattr, O_str(pvalue, no_recurse=no_recurse, seen=seen)
164
+ )
165
+ attrdesc_strs.append(desc)
166
+ s = "<%s %s>" % (o.__class__.__name__, ",".join(attrdesc_strs))
167
+ seen.remove(id(o))
168
+ return s
169
+
170
+ def copy(obj, *a, **kw):
171
+ ''' Convenient function to shallow copy an object with simple modifications.
172
+
173
+ Performs a shallow copy of `self` using copy.copy.
174
+
175
+ Treat all positional parameters as attribute names, and
176
+ replace those attributes with shallow copies of the original
177
+ attribute.
178
+
179
+ Treat all keyword arguments as (attribute,value) tuples and
180
+ replace those attributes with the supplied values.
181
+ '''
182
+ obj2 = copy0(obj)
183
+ for attr in a:
184
+ setattr(obj2, attr, copy(getattr(obj, attr)))
185
+ for attr, value in kw.items():
186
+ setattr(obj2, attr, value)
187
+ return obj2
188
+
189
+ def as_dict(o, selector=None):
190
+ ''' Return a dictionary with keys mapping to the values of the attributes of `o`.
191
+
192
+ Parameters:
193
+ * `o`: the object to map
194
+ * `selector`: the optional selection criterion
195
+
196
+ If `selector` is omitted or `None`, select "public" attributes,
197
+ those not commencing with an underscore.
198
+
199
+ If `selector` is a `str`, select attributes starting with `selector`.
200
+
201
+ Otherwise presume `selector` is callable
202
+ and select attributes `attr` where `selector(attr)` is true.
203
+ '''
204
+ if selector is None:
205
+ match = lambda attr: attr and not attr.startswith('_')
206
+ elif isinstance(selector, str):
207
+ match = lambda attr: attr.startswith(selector)
208
+ else:
209
+ match = selector
210
+ return {attr: getattr(o, attr) for attr in dir(o) if match(attr)}
211
+
212
+ @OBSOLETE("use cs.obj.as_dict")
213
+ def obj_as_dict(o, **kw):
214
+ ''' OBSOLETE convesion of an object to a `dict`. Please us `cs.obj.as_dict`.
215
+ '''
216
+ raise RuntimeError("please use cs.obj.as_dict")
217
+
218
+ class Proxy(object):
219
+ ''' An extremely simple proxy object
220
+ that passes all unmatched attribute accesses to the proxied object.
221
+
222
+ Note that setattr and delattr work directly on the proxy, not the proxied object.
223
+ '''
224
+
225
+ def __init__(self, other):
226
+ self._proxied = other
227
+
228
+ def __getattr__(self, attr):
229
+ _proxied = object.__getattribute__(self, '_proxied')
230
+ return getattr(_proxied, attr)
231
+
232
+ def __iter__(self):
233
+ _proxied = object.__getattribute__(self, '_proxied')
234
+ return iter(_proxied)
235
+
236
+ def __len__(self):
237
+ _proxied = object.__getattribute__(self, '_proxied')
238
+ return len(_proxied)
239
+
240
+ class TrackedClassMixin(object):
241
+ ''' A mixin to track all instances of a particular class.
242
+
243
+ This is aimed at checking the global state of objects of a
244
+ particular type, particularly states like counters. The
245
+ tracking is attached to the class itself.
246
+
247
+ The class to be tracked includes this mixin as a superclass and calls:
248
+
249
+ TrackedClassMixin.__init__(class_to_track)
250
+
251
+ from its __init__ method. Note that `class_to_track` is
252
+ typically the class name itself, not `type(self)` which would
253
+ track the specific subclass. At some relevant point one can call:
254
+
255
+ self.tcm_dump(class_to_track[, file])
256
+
257
+ `class_to_track` needs a `tcm_get_state` method to return the
258
+ salient information, such as this from cs.resources.MultiOpenMixin:
259
+
260
+ def tcm_get_state(self):
261
+ return {'opened': self.opened, 'opens': self._opens}
262
+
263
+ See cs.resources.MultiOpenMixin for example use.
264
+ '''
265
+
266
+ def __init__(self, cls):
267
+ try:
268
+ m = cls.__map
269
+ except AttributeError:
270
+ m = cls.__map = {}
271
+ m[id(self)] = self
272
+
273
+ def __state(self, cls):
274
+ return cls.tcm_get_state(self)
275
+
276
+ @staticmethod
277
+ def tcm_all_state(klass):
278
+ ''' Generator yielding tracking information
279
+ for objects of type `klass`
280
+ in the form `(o,state)`
281
+ where `o` if a tracked object
282
+ and `state` is the object's `get_tcm_state` method result.
283
+ '''
284
+ m = klass.__map
285
+ for o in m.values():
286
+ yield o, klass.__state(o, klass)
287
+
288
+ @staticmethod
289
+ def tcm_dump(klass, f=None):
290
+ ''' Dump the tracking information for `klass` to the file `f`
291
+ (default `sys.stderr`).
292
+ '''
293
+ if f is None:
294
+ f = sys.stderr
295
+ for o, state in TrackedClassMixin.tcm_all_state(klass):
296
+ print(str(type(o)), id(o), repr(state), file=f)
297
+
298
+ def singleton(registry, key, factory, fargs, fkwargs):
299
+ ''' Obtain an object for `key` via `registry` (a mapping of `key`=>object).
300
+ Return `(is_new,object)`.
301
+
302
+ If the `key` exists in the registry, return the associated object.
303
+ Otherwise create a new object by calling `factory(*fargs,**fkwargs)`
304
+ and store it as `key` in the `registry`.
305
+
306
+ The `registry` may be any mapping of `key`s to objects
307
+ but will usually be a `weakref.WeakValueDictionary`
308
+ in order that object references expire as normal,
309
+ allowing garbage collection.
310
+
311
+ *Note*: this function *is not* thread safe.
312
+ Multithreaded users should hold a mutex.
313
+
314
+ See the `SingletonMixin` class for a simple mixin to create
315
+ singleton classes,
316
+ which does provide thread safe operations.
317
+ '''
318
+ try:
319
+ instance = registry[key]
320
+ is_new = False
321
+ except KeyError:
322
+ instance = factory(*fargs, **fkwargs)
323
+ registry[key] = instance
324
+ is_new = True
325
+ return is_new, instance
326
+
327
+ # pylint: disable=too-few-public-methods
328
+ class SingletonMixin:
329
+ ''' A mixin turning a subclass into a singleton factory.
330
+
331
+ *Note*: this mixin overrides `object.__new__`
332
+ and may not play well with other classes which override `__new__`.
333
+
334
+ *Warning*: because of the mechanics of `__new__`,
335
+ the instance's `__init__` method will always be called
336
+ after `__new__`,
337
+ even when a preexisting object is returned.
338
+ Therefore that method should be sensible
339
+ even for an already initialised
340
+ and probably subsequently modified object.
341
+
342
+ My suggested approach is to access some attribute,
343
+ and preemptively return if it already exists.
344
+ Example:
345
+
346
+ def __init__(self, x, y):
347
+ if 'x' in self.__dict__:
348
+ return
349
+ self.x = x
350
+ self.y = y
351
+
352
+ *Note*: we probe `self.__dict__` above to accomodate classes
353
+ with a `__getattr__` method.
354
+
355
+ *Note*: each class registry has a lock,
356
+ which ensures that reuse of an object
357
+ in multiple threads will call the `__init__` method
358
+ in a thread safe serialised fashion.
359
+
360
+ Implementation requirements:
361
+ a subclass should:
362
+ * provide a method `_singleton_key(*args,**kwargs)`
363
+ returning a key for use in the single registry,
364
+ computed from the positional and keyword arguments
365
+ supplied on instance creation
366
+ i.e. those which `__init__` would normally receive.
367
+ This should have the same signature as `__init__`
368
+ but using `cls` instead of `self`.
369
+ * provide a normal `__init__` method
370
+ which can be safely called again
371
+ after some earlier initialisation.
372
+
373
+ This class is thread safe for the registry operations.
374
+
375
+ Example:
376
+
377
+ class Pool(SingletonMixin):
378
+
379
+ @classmethod
380
+ def _singleton_key(cls, foo, bah=3):
381
+ return foo, bah
382
+
383
+ def __init__(self, foo, bah=3):
384
+ if hasattr(self, 'foo'):
385
+ return
386
+ ... normal __init__ stuff here ...
387
+ self.foo = foo
388
+ ...
389
+ '''
390
+
391
+ # This lock is used to control setup of the per-class registry.
392
+ # It is shared across all subclasses, but that bypasses any need to call an
393
+ # __init__ for this mixin. In mitigation, the lock is only used if the class
394
+ # does not yet have a registry.
395
+ __global_lock = Lock()
396
+
397
+ @classmethod
398
+ def _singleton_get_registry(cls):
399
+ ''' Obtain the class singleton registry, creating it on first use.
400
+ '''
401
+ try:
402
+ registry = cls._singleton_registry
403
+ except AttributeError:
404
+ with cls.__global_lock:
405
+ try:
406
+ registry = cls._singleton_registry
407
+ except AttributeError:
408
+ # create the registry and give it its own mutex and multiindex
409
+ registry = cls._singleton_registry = WeakValueDictionary()
410
+ registry._singleton_lock = Lock()
411
+ registry._singleton_also_keys = defaultdict(WeakValueDictionary)
412
+ return registry
413
+
414
+ def __new__(cls, *a, **kw):
415
+ ''' Prepare a new instance of `cls` if required.
416
+ Return the instance.
417
+
418
+ This creates the class registry if missing,
419
+ prepares a key from `cls._singleton_key`,
420
+ then returns the entry from the registry is present,
421
+ or creates a new entry if not.
422
+ Note: if the key is `None` a new entry is always created
423
+ and not recorded in the registry.
424
+ '''
425
+ super_new = super().__new__
426
+
427
+ # pylint: disable=unused-argument
428
+ def factory(*fargs, **fkwargs):
429
+ ''' Prepare a new object; does not yet call `__init__`.
430
+ This accepts arguments to support use via the `singleton()` function.
431
+ '''
432
+ return super_new(cls)
433
+
434
+ okey = cls._singleton_key(*a, **kw)
435
+ if okey is None:
436
+ # if the returned key is None we always make a new instance
437
+ # and do not register in the registry
438
+ instance = factory()
439
+ else:
440
+ # normal behaviour:
441
+ # reuse an existing instance or make a new one
442
+ registry = cls._singleton_get_registry()
443
+ with registry._singleton_lock:
444
+ is_new, instance = singleton(registry, okey, factory, (), {})
445
+ if is_new:
446
+ instance._SingletonMixin_key = okey
447
+ else:
448
+ assert instance._SingletonMixin_key == okey
449
+ return instance
450
+
451
+ # default hash and equality methods
452
+ def __hash__(self):
453
+ return hash(self._SingletonMixin_key)
454
+
455
+ def __eq__(self, other):
456
+ return self is other
457
+
458
+ @classmethod
459
+ def singleton_also_by(cls, also_key, key):
460
+ ''' Obtain a singleton by a secondary key.
461
+ Return the instance or `None`.
462
+
463
+ Parameters:
464
+ * `also_key`: the name of the secondary key index
465
+ * `key`: the key for the index
466
+ '''
467
+ registry = cls._singleton_get_registry()
468
+ with registry._singleton_lock:
469
+ return registry._singleton_also_keys[also_key].get(key)
470
+
471
+ # pylint: disable=no-self-use
472
+ def _singleton_also_indexmap(self):
473
+ ''' Return a mapping of secondary key names and their matching key values.
474
+ '''
475
+ return {}
476
+
477
+ def _singleton_also_index(self):
478
+ ''' Return a mapping of secondary key names and their matching key values.
479
+ '''
480
+ registry = self._singleton_get_registry()
481
+ with registry._singleton_lock:
482
+ for also_key, key in self._singleton_also_indexmap().items():
483
+ registry._singleton_also_keys[also_key][key] = self
484
+
485
+ @classmethod
486
+ def _singleton_instances(cls):
487
+ ''' Return a list of the current class instances.
488
+ '''
489
+ try:
490
+ registry = cls._singleton_registry
491
+ except AttributeError:
492
+ return []
493
+ else:
494
+ return list(
495
+ filter(
496
+ lambda obj: obj is not None,
497
+ map(lambda ref: ref(), registry.valuerefs())
498
+ )
499
+ )
500
+
501
+ class Sentinel:
502
+ ''' A simple class for named sentinels whose `str()` is just the name
503
+ and whose `==` uses `is`.
504
+
505
+ Example:
506
+
507
+ >>> from cs.obj import Sentinel
508
+ >>> MISSING = Sentinel("MISSING")
509
+ >>> print(MISSING)
510
+ MISSING
511
+ >>> other = Sentinel("other")
512
+ >>> MISSING == other
513
+ False
514
+ >>> MISSING == MISSING
515
+ True
516
+ '''
517
+
518
+ __slots__ = 'name',
519
+
520
+ def __init__(self, name):
521
+ self.name = name
522
+
523
+ def __str__(self):
524
+ return self.name
525
+
526
+ def __repr__(self):
527
+ return "%s(%r)" % (self.__class__.__name__, self.name)
528
+
529
+ def __eq__(self, other):
530
+ return self is other
531
+
532
+ def public_subclasses(cls):
533
+ ''' Return a list of the subclasses of `cls` which has public names.
534
+ '''
535
+ classes = []
536
+ q = list(cls.__subclasses__())
537
+ while q:
538
+ subcls = q.pop(0)
539
+ if not issubclass(subcls, cls):
540
+ continue
541
+ if not subcls.__name__.startswith('_'):
542
+ classes.append(subcls)
543
+ ##print(cls, "classes +", subcls)
544
+ q.extend(subcls.__subclasses__())
545
+ return classes
546
+
547
+ if __name__ == '__main__':
548
+ import cs.obj_tests
549
+ cs.obj_tests.selftest(sys.argv)
@@ -0,0 +1,329 @@
1
+ Metadata-Version: 2.1
2
+ Name: cs.obj
3
+ Version: 20241005
4
+ Summary: Convenience facilities for objects.
5
+ Author-email: Cameron Simpson <cs@cskk.id.au>
6
+ License: GNU General Public License v3 or later (GPLv3+)
7
+ Project-URL: Monorepo Hg/Mercurial Mirror, https://hg.sr.ht/~cameron-simpson/css
8
+ Project-URL: Monorepo Git Mirror, https://github.com/cameron-simpson/css
9
+ Project-URL: MonoRepo Commits, https://bitbucket.org/cameron_simpson/css/commits/branch/main
10
+ Project-URL: Source, https://github.com/cameron-simpson/css/blob/main/lib/python/cs/obj.py
11
+ Keywords: python2,python3
12
+ Classifier: Programming Language :: Python
13
+ Classifier: Programming Language :: Python :: 2
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Development Status :: 4 - Beta
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
20
+ Description-Content-Type: text/markdown
21
+ Requires-Dist: cs.deco >=20241003
22
+ Requires-Dist: cs.py3 >=20220523
23
+
24
+ Convenience facilities for objects.
25
+
26
+ *Latest release 20241005*:
27
+ New public_subclasses(cls) returning all subclasses with public names.
28
+
29
+ ## <a name="as_dict"></a>`as_dict(o, selector=None)`
30
+
31
+ Return a dictionary with keys mapping to the values of the attributes of `o`.
32
+
33
+ Parameters:
34
+ * `o`: the object to map
35
+ * `selector`: the optional selection criterion
36
+
37
+ If `selector` is omitted or `None`, select "public" attributes,
38
+ those not commencing with an underscore.
39
+
40
+ If `selector` is a `str`, select attributes starting with `selector`.
41
+
42
+ Otherwise presume `selector` is callable
43
+ and select attributes `attr` where `selector(attr)` is true.
44
+
45
+ ## <a name="copy"></a>`copy(obj, *a, **kw)`
46
+
47
+ Convenient function to shallow copy an object with simple modifications.
48
+
49
+ Performs a shallow copy of `self` using copy.copy.
50
+
51
+ Treat all positional parameters as attribute names, and
52
+ replace those attributes with shallow copies of the original
53
+ attribute.
54
+
55
+ Treat all keyword arguments as (attribute,value) tuples and
56
+ replace those attributes with the supplied values.
57
+
58
+ ## <a name="flavour"></a>`flavour(obj)`
59
+
60
+ Return constants indicating the ``flavour'' of an object:
61
+ * `T_MAP`: DictType, DictionaryType, objects with an __keys__ or keys attribute.
62
+ * `T_SEQ`: TupleType, ListType, objects with an __iter__ attribute.
63
+ * `T_SCALAR`: Anything else.
64
+
65
+ ## <a name="O"></a>Class `O(types.SimpleNamespace)`
66
+
67
+ The `O` class is now obsolete, please subclass `types.SimpleNamespace`
68
+ or use a dataclass.
69
+
70
+ ## <a name="O_attritems"></a>`O_attritems(o)`
71
+
72
+ Generator yielding `(attr,value)` for relevant attributes of `o`.
73
+
74
+ ## <a name="O_attrs"></a>`O_attrs(o)`
75
+
76
+ Yield attribute names from `o` which are pertinent to `O_str`.
77
+
78
+ Note: this calls `getattr(o,attr)` to inspect it in order to
79
+ prune callables.
80
+
81
+ ## <a name="O_merge"></a>`O_merge(o, _conflict=None, _overwrite=False, **kw)`
82
+
83
+ Merge key:value pairs from a mapping into an object.
84
+
85
+ Ignore keys that do not start with a letter.
86
+ New attributes or attributes whose values compare equal are
87
+ merged in. Unequal values are passed to:
88
+
89
+ _conflict(o, attr, old_value, new_value)
90
+
91
+ to resolve the conflict. If _conflict is omitted or None
92
+ then the new value overwrites the old if _overwrite is true.
93
+
94
+ ## <a name="O_str"></a>`O_str(o, no_recurse=False, seen=None)`
95
+
96
+ Return a `str` representation of the object `o`.
97
+
98
+ Parameters:
99
+ * `o`: the object to describe.
100
+ * `no_recurse`: if true, do not recurse into the object's structure.
101
+ Default: `False`.
102
+ * `seen`: a set of previously sighted objects
103
+ to prevent recursion loops.
104
+
105
+ ## <a name="obj_as_dict"></a>`obj_as_dict(o, **kw)`
106
+
107
+ OBSOLETE obj_as_dict
108
+
109
+ OBSOLETE convesion of an object to a `dict`. Please us `cs.obj.as_dict`.
110
+
111
+ ## <a name="Proxy"></a>Class `Proxy`
112
+
113
+ An extremely simple proxy object
114
+ that passes all unmatched attribute accesses to the proxied object.
115
+
116
+ Note that setattr and delattr work directly on the proxy, not the proxied object.
117
+
118
+ ## <a name="public_subclasses"></a>`public_subclasses(cls)`
119
+
120
+ Return a list of the subclasses of `cls` which has public names.
121
+
122
+ ## <a name="Sentinel"></a>Class `Sentinel`
123
+
124
+ A simple class for named sentinels whose `str()` is just the name
125
+ and whose `==` uses `is`.
126
+
127
+ Example:
128
+
129
+ >>> from cs.obj import Sentinel
130
+ >>> MISSING = Sentinel("MISSING")
131
+ >>> print(MISSING)
132
+ MISSING
133
+ >>> other = Sentinel("other")
134
+ >>> MISSING == other
135
+ False
136
+ >>> MISSING == MISSING
137
+ True
138
+
139
+ ## <a name="singleton"></a>`singleton(registry, key, factory, fargs, fkwargs)`
140
+
141
+ Obtain an object for `key` via `registry` (a mapping of `key`=>object).
142
+ Return `(is_new,object)`.
143
+
144
+ If the `key` exists in the registry, return the associated object.
145
+ Otherwise create a new object by calling `factory(*fargs,**fkwargs)`
146
+ and store it as `key` in the `registry`.
147
+
148
+ The `registry` may be any mapping of `key`s to objects
149
+ but will usually be a `weakref.WeakValueDictionary`
150
+ in order that object references expire as normal,
151
+ allowing garbage collection.
152
+
153
+ *Note*: this function *is not* thread safe.
154
+ Multithreaded users should hold a mutex.
155
+
156
+ See the `SingletonMixin` class for a simple mixin to create
157
+ singleton classes,
158
+ which does provide thread safe operations.
159
+
160
+ ## <a name="SingletonMixin"></a>Class `SingletonMixin`
161
+
162
+ A mixin turning a subclass into a singleton factory.
163
+
164
+ *Note*: this mixin overrides `object.__new__`
165
+ and may not play well with other classes which override `__new__`.
166
+
167
+ *Warning*: because of the mechanics of `__new__`,
168
+ the instance's `__init__` method will always be called
169
+ after `__new__`,
170
+ even when a preexisting object is returned.
171
+ Therefore that method should be sensible
172
+ even for an already initialised
173
+ and probably subsequently modified object.
174
+
175
+ My suggested approach is to access some attribute,
176
+ and preemptively return if it already exists.
177
+ Example:
178
+
179
+ def __init__(self, x, y):
180
+ if 'x' in self.__dict__:
181
+ return
182
+ self.x = x
183
+ self.y = y
184
+
185
+ *Note*: we probe `self.__dict__` above to accomodate classes
186
+ with a `__getattr__` method.
187
+
188
+ *Note*: each class registry has a lock,
189
+ which ensures that reuse of an object
190
+ in multiple threads will call the `__init__` method
191
+ in a thread safe serialised fashion.
192
+
193
+ Implementation requirements:
194
+ a subclass should:
195
+ * provide a method `_singleton_key(*args,**kwargs)`
196
+ returning a key for use in the single registry,
197
+ computed from the positional and keyword arguments
198
+ supplied on instance creation
199
+ i.e. those which `__init__` would normally receive.
200
+ This should have the same signature as `__init__`
201
+ but using `cls` instead of `self`.
202
+ * provide a normal `__init__` method
203
+ which can be safely called again
204
+ after some earlier initialisation.
205
+
206
+ This class is thread safe for the registry operations.
207
+
208
+ Example:
209
+
210
+ class Pool(SingletonMixin):
211
+
212
+ @classmethod
213
+ def _singleton_key(cls, foo, bah=3):
214
+ return foo, bah
215
+
216
+ def __init__(self, foo, bah=3):
217
+ if hasattr(self, 'foo'):
218
+ return
219
+ ... normal __init__ stuff here ...
220
+ self.foo = foo
221
+ ...
222
+
223
+ *`SingletonMixin.__hash__(self)`*:
224
+ default hash and equality methods
225
+
226
+ *`SingletonMixin.singleton_also_by(also_key, key)`*:
227
+ Obtain a singleton by a secondary key.
228
+ Return the instance or `None`.
229
+
230
+ Parameters:
231
+ * `also_key`: the name of the secondary key index
232
+ * `key`: the key for the index
233
+
234
+ ## <a name="TrackedClassMixin"></a>Class `TrackedClassMixin`
235
+
236
+ A mixin to track all instances of a particular class.
237
+
238
+ This is aimed at checking the global state of objects of a
239
+ particular type, particularly states like counters. The
240
+ tracking is attached to the class itself.
241
+
242
+ The class to be tracked includes this mixin as a superclass and calls:
243
+
244
+ TrackedClassMixin.__init__(class_to_track)
245
+
246
+ from its __init__ method. Note that `class_to_track` is
247
+ typically the class name itself, not `type(self)` which would
248
+ track the specific subclass. At some relevant point one can call:
249
+
250
+ self.tcm_dump(class_to_track[, file])
251
+
252
+ `class_to_track` needs a `tcm_get_state` method to return the
253
+ salient information, such as this from cs.resources.MultiOpenMixin:
254
+
255
+ def tcm_get_state(self):
256
+ return {'opened': self.opened, 'opens': self._opens}
257
+
258
+ See cs.resources.MultiOpenMixin for example use.
259
+
260
+ *`TrackedClassMixin.tcm_all_state(klass)`*:
261
+ Generator yielding tracking information
262
+ for objects of type `klass`
263
+ in the form `(o,state)`
264
+ where `o` if a tracked object
265
+ and `state` is the object's `get_tcm_state` method result.
266
+
267
+ *`TrackedClassMixin.tcm_dump(klass, f=None)`*:
268
+ Dump the tracking information for `klass` to the file `f`
269
+ (default `sys.stderr`).
270
+
271
+ # Release Log
272
+
273
+
274
+
275
+ *Release 20241005*:
276
+ New public_subclasses(cls) returning all subclasses with public names.
277
+
278
+ *Release 20220918*:
279
+ * SingletonMixin: change example to probe self__dict__ instead of hasattr, faster and less fragile.
280
+ * New Sentinel class for named sentinel objects, equal only to their own instance.
281
+
282
+ *Release 20220530*:
283
+ SingletonMixin: add default __hash__ and __eq__ methods to support dict and set membership.
284
+
285
+ *Release 20210717*:
286
+ SingletonMixin: if cls._singleton_key returns None we always make a new instance and do not register it.
287
+
288
+ *Release 20210306*:
289
+ SingletonMixin: make singleton_also_by() a public method.
290
+
291
+ *Release 20210131*:
292
+ 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.
293
+
294
+ *Release 20210122*:
295
+ SingletonMixin: new _singleton_instances() method returning a list of the current instances.
296
+
297
+ *Release 20201227*:
298
+ SingletonMixin: correctly invoke __new__, a surprisingly fiddly task to get right.
299
+
300
+ *Release 20201021*:
301
+ * @OBSOLETE(obj_as_dict), recommend "as_dict()".
302
+ * [BREAKING] change as_dict() to accept a single optional selector instead of various mutually exclusive keywords.
303
+
304
+ *Release 20200716*:
305
+ SingletonMixin: no longer require special _singleton_init method, reuse default __init__ implicitly through __new__ mechanics.
306
+
307
+ *Release 20200517*:
308
+ Documentation improvements.
309
+
310
+ *Release 20200318*:
311
+ * Replace obsolete O class with a new subclass of SimpleNamespace which issues a warning.
312
+ * New singleton() generic factory function and SingletonMixin mixin class for making singleton classes.
313
+
314
+ *Release 20190103*:
315
+ * New mixin class TrackedClassMixin to track all instances of a particular class.
316
+ * Documentation updates.
317
+
318
+ *Release 20170904*:
319
+ Minor cleanups.
320
+
321
+ *Release 20160828*:
322
+ * Use "install_requires" instead of "requires" in DISTINFO.
323
+ * Minor tweaks.
324
+
325
+ *Release 20150118*:
326
+ move long_description into cs/README-obj.rst
327
+
328
+ *Release 20150110*:
329
+ cleaned out some old junk, readied metadata for PyPI
@@ -0,0 +1,5 @@
1
+ cs/obj.py,sha256=I5lKpOYOKM0wwcKt33_PQsEPq2hTZ1zgCbw-7taz7Ow,16672
2
+ cs.obj-20241005.dist-info/METADATA,sha256=RWAMIBYvUldMHQMe-44SA0TTYh1v9jR3v4D3prNW9m4,10743
3
+ cs.obj-20241005.dist-info/WHEEL,sha256=y4mX-SOX4fYIkonsAGA5N0Oy-8_gI4FXw5HNI1xqvWg,91
4
+ cs.obj-20241005.dist-info/top_level.txt,sha256=MJn10B_hUOb4f5hIJP5wKj_mMYsOQ6NUWqo9vSLmwcQ,3
5
+ cs.obj-20241005.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (70.2.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ cs