adding sentinel metaclass example

This commit is contained in:
Luciano Ramalho
2021-05-23 22:12:13 -03:00
parent 8a330d822b
commit f248baf418
14 changed files with 220 additions and 1 deletions

View 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

View 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***'