Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow NewType subclassing NewType. #3465

Merged
merged 1 commit into from
May 28, 2017
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
4 changes: 0 additions & 4 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -1822,10 +1822,6 @@ def check_newtype_args(self, name: str, call: CallExpr, context: Context) -> Opt
return None
old_type = self.anal_type(unanalyzed_type)

if isinstance(old_type, Instance) and old_type.type.is_newtype:
self.fail("Argument 2 to NewType(...) cannot be another NewType", context)
has_failed = True

return None if has_failed else old_type

def build_newtype_typeinfo(self, name: str, old_type: Type, base_type: Instance) -> TypeInfo:
Expand Down
32 changes: 23 additions & 9 deletions test-data/unit/check-newtype.test
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,29 @@ y = Bar2(42)
y = func3(x)
[out]

[case testNewTypeWithNewType]
from typing import NewType
A = NewType('A', int)
B = NewType('B', A)
C = A
D = C
E = NewType('E', D)

a = A(1)
b = B(a)
e = E(a)

def funca(a: A) -> None: ...
def funcb(b: B) -> None: ...

funca(a)
funca(b)
funca(e)
funcb(a) # E: Argument 1 to "funcb" has incompatible type "A"; expected "B"
funcb(b)
funcb(e) # E: Argument 1 to "funcb" has incompatible type "E"; expected "B"

[out]

-- Make sure NewType works as expected in a variety of different scopes/across files

Expand Down Expand Up @@ -279,15 +302,6 @@ main:3: error: Argument 2 to NewType(...) must be subclassable (got T?)
main:3: error: Invalid type "__main__.T"
main:4: error: Invalid type "__main__.T"

[case testNewTypeWithNewTypeFails]
from typing import NewType
A = NewType('A', int)
B = NewType('B', A) # E: Argument 2 to NewType(...) cannot be another NewType
C = A
D = C
E = NewType('E', D) # E: Argument 2 to NewType(...) cannot be another NewType
[out]

[case testNewTypeRedefiningVariablesFails]
from typing import NewType

Expand Down