| 1 |
from typing import Any, Tuple, Type, Union |
| 2 |
|
| 3 |
__all__ = [ |
| 4 |
"Description", |
| 5 |
"is_description", |
| 6 |
"register_description", |
| 7 |
"unregister_description", |
| 8 |
] |
| 9 |
|
| 10 |
|
| 11 |
class Description: |
| 12 |
"""Type checker for human readable descriptions. |
| 13 |
|
| 14 |
By default, only ordinary strings are accepted as descriptions, |
| 15 |
but you can register() other classes that will also be allowed, |
| 16 |
e.g. to support lazy string objects that are evaluated only at runtime. |
| 17 |
If you register(object), any object will be allowed as description. |
| 18 |
""" |
| 19 |
|
| 20 |
bases: Union[Type[Any], Tuple[Type[Any], ...]] = str |
| 21 |
|
| 22 |
@classmethod |
| 23 |
def isinstance(cls, obj: Any) -> bool: |
| 24 |
return isinstance(obj, cls.bases) |
| 25 |
|
| 26 |
@classmethod |
| 27 |
def register(cls, base: Type[Any]) -> None: |
| 28 |
"""Register a class that shall be accepted as a description.""" |
| 29 |
if not isinstance(base, type): |
| 30 |
raise TypeError("Only types can be registered.") |
| 31 |
if base is object: |
| 32 |
cls.bases = object |
| 33 |
elif cls.bases is object: |
| 34 |
cls.bases = base |
| 35 |
elif not isinstance(cls.bases, tuple): |
| 36 |
if base is not cls.bases: |
| 37 |
cls.bases = (cls.bases, base) |
| 38 |
elif base not in cls.bases: |
| 39 |
cls.bases += (base,) |
| 40 |
|
| 41 |
@classmethod |
| 42 |
def unregister(cls, base: Type[Any]) -> None: |
| 43 |
"""Unregister a class that shall no more be accepted as a description.""" |
| 44 |
if not isinstance(base, type): |
| 45 |
raise TypeError("Only types can be unregistered.") |
| 46 |
if isinstance(cls.bases, tuple): |
| 47 |
if base in cls.bases: # pragma: no branch |
| 48 |
cls.bases = tuple(b for b in cls.bases if b is not base) |
| 49 |
if not cls.bases: |
| 50 |
cls.bases = object |
| 51 |
elif len(cls.bases) == 1: |
| 52 |
cls.bases = cls.bases[0] |
| 53 |
elif cls.bases is base: |
| 54 |
cls.bases = object |
| 55 |
|
| 56 |
|
| 57 |
is_description = Description.isinstance |
| 58 |
register_description = Description.register |
| 59 |
unregister_description = Description.unregister |