Created
December 14, 2017 18:47
-
-
Save Deepwalker/d989e6e2ba769ba121847f34949b07a1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import inspect | |
from dataclasses import dataclass, field | |
class Union(type): | |
def __new__(cls, name, bases, namespace, **kwds): | |
print('Init new Union') | |
new_namespace = {} | |
for attr_name, value in namespace.items(): | |
print(name, value) | |
if inspect.isclass(value): | |
exc_inherit = type(value.__name__, (value, BaseException), {}) | |
new_namespace[attr_name] = dataclass(exc_inherit) | |
# new_namespace[name] = dataclass(value) | |
new_namespace['is' + attr_name] = lambda arg: isinstance(arg, value) | |
else: | |
new_namespace[attr_name] = value | |
result = type.__new__(cls, name, bases, new_namespace) | |
return result | |
def raise_type(cls, value): | |
raise value | |
class JSON(metaclass=Union): | |
class Str: | |
value: str | |
class Name: | |
value: str | |
class Dict: | |
value: dict | |
class List: | |
value: list | |
jstr = JSON.Str('some text') | |
jlist = JSON.List([ | |
JSON.Str('list entry') | |
]) | |
if JSON.isStr(jstr): | |
print('Str:', jstr.value) | |
if JSON.isList(jlist): | |
print('List:', jstr.value) | |
try: | |
JSON.raise_type(jlist) | |
except JSON.Str as v: | |
print('Str:', v) | |
except JSON.List as v: | |
print('List:', v) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment