Completed
Pull Request — master (#872)
by
unknown
01:32
created

zipline.utils.Sentinel.__repr__()   A

Complexity

Conditions 1

Size

Total Lines 2

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 1
dl 0
loc 2
rs 10
1
"""
2
Construction of sentinel objects.
3
4
Sentinel objects are used when you only care to check for object identity.
5
"""
6
import sys
7
8
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