Yurii Karabas <[email protected]> added the comment:
What about to return callable object instead of function from a
`typing.NewType`?
It will look something like this:
```
class _NewType:
__slots__ = ('__name__', '__supertype__')
def __init__(self, name, supertype):
self.__name__ = name
self.__supertype__ = supertype
def __call__(self, val):
return val
def __or__(self, other):
return Union[self, other]
def __ror__(self, other):
return Union[other, self]
def NewType(name, tp):
"""NewType creates simple unique types with almost zero
runtime overhead. NewType(name, tp) is considered a subtype of tp
by static type checkers. At runtime, NewType(name, tp) returns
a dummy callable object that simply returns its argument. Usage::
UserId = NewType('UserId', int)
def name_by_id(user_id: UserId) -> str:
...
UserId('user') # Fails type check
name_by_id(42) # Fails type check
name_by_id(UserId(42)) # OK
num = UserId(5) + 1 # type: int
"""
return _NewType(name, tp)
```
With such implementation `__or__` will be available for a NewType and actually
because of __slots__ size of object will be 48 bytes (with sys.getsizeof) which
is less than current 144 bytes (if memory is important).
----------
nosy: +uriyyo
_______________________________________
Python tracker <[email protected]>
<https://bugs.python.org/issue44353>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com