adding sentinel metaclass example
This commit is contained in:
24
25-class-metaprog/sentinel/sentinel.py
Normal file
24
25-class-metaprog/sentinel/sentinel.py
Normal file
@@ -0,0 +1,24 @@
|
||||
"""
|
||||
|
||||
>>> class Missing(Sentinel): pass
|
||||
>>> Missing
|
||||
<Missing>
|
||||
>>> class CustomRepr(Sentinel):
|
||||
... repr = '*** sentinel ***'
|
||||
...
|
||||
>>> CustomRepr
|
||||
*** sentinel ***
|
||||
|
||||
"""
|
||||
|
||||
class SentinelMeta(type):
|
||||
def __repr__(cls):
|
||||
try:
|
||||
return cls.repr
|
||||
except AttributeError:
|
||||
return f'<{cls.__name__}>'
|
||||
|
||||
class Sentinel(metaclass=SentinelMeta):
|
||||
def __new__(cls):
|
||||
return cls
|
||||
|
||||
22
25-class-metaprog/sentinel/sentinel_test.py
Normal file
22
25-class-metaprog/sentinel/sentinel_test.py
Normal file
@@ -0,0 +1,22 @@
|
||||
from sentinel import Sentinel
|
||||
|
||||
class PlainSentinel(Sentinel): pass
|
||||
|
||||
|
||||
class SentinelCustomRepr(Sentinel):
|
||||
repr = '***SentinelRepr***'
|
||||
|
||||
|
||||
def test_repr():
|
||||
assert repr(PlainSentinel) == '<PlainSentinel>'
|
||||
|
||||
|
||||
def test_pickle():
|
||||
from pickle import dumps, loads
|
||||
s = dumps(PlainSentinel)
|
||||
ps = loads(s)
|
||||
assert ps is PlainSentinel
|
||||
|
||||
def test_custom_repr():
|
||||
assert repr(SentinelCustomRepr) == '***SentinelRepr***'
|
||||
|
||||
Reference in New Issue
Block a user