This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author uriyyo
Recipients domdfcoding, joperez, uriyyo
Date 2021-06-10.11:29:35
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1623324575.14.0.971496853521.issue44353@roundup.psfhosted.org>
In-reply-to
Content
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).
History
Date User Action Args
2021-06-10 11:29:35uriyyosetrecipients: + uriyyo, joperez, domdfcoding
2021-06-10 11:29:35uriyyosetmessageid: <1623324575.14.0.971496853521.issue44353@roundup.psfhosted.org>
2021-06-10 11:29:35uriyyolinkissue44353 messages
2021-06-10 11:29:35uriyyocreate