Conditions | 6 |
Total Lines | 45 |
Lines | 0 |
Ratio | 0 % |
1 | """ |
||
9 | def sentinel(name, doc=None): |
||
10 | try: |
||
11 | value = sentinel._cache[name] # memoized |
||
12 | except KeyError: |
||
13 | pass |
||
14 | else: |
||
15 | if doc == value.__doc__: |
||
16 | return value |
||
17 | |||
18 | raise ValueError( |
||
19 | 'attempted to create sentinel with a used name and a different' |
||
20 | ' docstring: %r\noriginal docstring:\n%s' % (name, value.__doc__), |
||
21 | ) |
||
22 | |||
23 | @object.__new__ # bind a single instance to the name 'Sentinel' |
||
24 | class Sentinel(object): |
||
25 | __doc__ = doc |
||
26 | __slots__ = ('__weakref__',) |
||
27 | __name__ = name |
||
28 | |||
29 | def __new__(cls): |
||
30 | raise TypeError("Can't construct new instances of %r" % name) |
||
31 | |||
32 | def __repr__(self): |
||
33 | return 'sentinel(%r)' % name |
||
34 | |||
35 | def __reduce__(self): |
||
36 | return sentinel, (name, doc) |
||
37 | |||
38 | def __deepcopy__(self, _memo): |
||
39 | return self |
||
40 | |||
41 | def __copy__(self): |
||
42 | return self |
||
43 | |||
44 | cls = type(Sentinel) |
||
45 | try: |
||
46 | # traverse up one frame to find the module where this is defined |
||
47 | cls.__module__ = sys._getframe(1).f_globals['__name__'] |
||
48 | except (AttributeError, ValueError, KeyError): |
||
49 | # Couldn't get the name from the calling scope, just use None. |
||
50 | cls.__module__ = None |
||
51 | |||
52 | sentinel._cache[name] = Sentinel # cache result |
||
53 | return Sentinel |
||
54 | sentinel._cache = {} |
||
55 |