Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions 20 Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -3691,6 +3691,26 @@ def test_errors(self):
class D(UserName):
pass

def test_or(self):
UserId = NewType('UserId', int)

self.assertEqual(UserId | int, Union[UserId, int])
self.assertEqual(int | UserId, Union[int, UserId])

self.assertEqual(get_args(UserId | int), (UserId, int))
self.assertEqual(get_args(int | UserId), (int, UserId))
Comment on lines +3697 to +3701

@Fidget-Spinner Fidget-Spinner Jul 20, 2021

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this doesn't test for the bug the user is reporting. In fact without this PR, these tests should all work, just instead of being typing.Union, it is types.Union (because int implements __or__). So the test won't be able to detect a regression.

The bug reported is that UserId1 | UserId2 won't work, because they both don't implement __or__.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right, we should add tests to cover case when there are two NewType.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will open another PR with more tests. I was not expecting that it will be merged so fast)


def test_special_attrs(self):
UserId = NewType('UserId', int)

self.assertEqual(UserId.__name__, 'UserId')
self.assertEqual(UserId.__qualname__, 'UserId')
self.assertEqual(UserId.__module__, __name__)

def test_repr(self):
UserId = NewType('UserId', int)

self.assertEqual(repr(UserId), f'{__name__}.UserId')

class NamedTupleTests(BaseTestCase):
class NestedEmployee(NamedTuple):
Expand Down
27 changes: 22 additions & 5 deletions 27 Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1374,6 +1374,12 @@ def _no_init(self, *args, **kwargs):
if type(self)._is_protocol:
raise TypeError('Protocols cannot be instantiated')

def _callee(depth=2, default=None):
try:
return sys._getframe(depth).f_globals['__name__']
except (AttributeError, ValueError): # For platforms without _getframe()
return default


def _allow_reckless_class_checks(depth=3):
"""Allow instance and class checks for special stdlib modules.
Expand Down Expand Up @@ -2350,7 +2356,7 @@ class body be required.
TypedDict.__mro_entries__ = lambda bases: (_TypedDict,)


def NewType(name, tp):
class NewType:
"""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
Expand All @@ -2369,12 +2375,23 @@ def name_by_id(user_id: UserId) -> str:
num = UserId(5) + 1 # type: int
"""

def new_type(x):
def __init__(self, name, tp):
self.__name__ = name
self.__qualname__ = name
self.__module__ = _callee(default='typing')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That makes it rather slow but I guess __module__ is actually helpful.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It will be executed only once when NewType defined. I think it should not dramatically effect performance.

self.__supertype__ = tp

def __repr__(self):
return f'{self.__module__}.{self.__qualname__}'

def __call__(self, x):
return x

new_type.__name__ = name
new_type.__supertype__ = tp
return new_type
def __or__(self, other):
return Union[self, other]

def __ror__(self, other):
return Union[other, self]


# Python-version-specific alias (Python 2: unicode; Python 3: str)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Refactor ``typing.NewType`` from function into callable class. Patch
provided by Yurii Karabas.
Morty Proxy This is a proxified and sanitized view of the page, visit original site.