-
-
Notifications
You must be signed in to change notification settings - Fork 29.9k
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
Improving the error message when subclassing NewType #90328
Comments
I'd like to propose making the error message when subclassing typing.NewType much more understandable. Currently it looks like:
But I think we could do much better by adding mro_entries to the class and then just having that raise a TypeError telling users they cannot subclass NewType and they are probably looking for |
This seems like a good idea to me. I will send a PR for others to judge :) |
Oh, please, go ahead! :) |
Do you have evidence that people make this particular mistake often? And that the suggested solution is indeed what they should use? Why would you want to subclass UserId? Do we have examples of other error messages split across two lines like this? |
I was just trying to implement something that I thought had a non-obvious error message and isn't necessarily initially obvious if you have the idea that NewType creates a new type/class. The documentation suggests this is what you should be doing instead of subclassing it
No if you want me to remove it thats fine by me. |
Weird, the docs you cite claims # Also does not typecheck
ProUserId = NewType('ProUserId', UserId) but when I try it, it works at runtime and passes mypy (even with --strict) and also pyright. So maybe those docs are incorrect? I can't find anything in PEP-484 about this. In any case I'd drop the newline in the message -- other "Did you mean" errors don't have those. |
Mypy even has an explicit test that NewType of NewType should work: https://github.com/python/mypy/blob/f96446ce2f99a86210b21d39c7aec4b13a8bfc66/test-data/unit/check-newtype.test#L162-L165 I tend to agree with this behavior. This allows us to create complex type-safe DSLs: from typing import NewType
UserId = NewType('UserId', int)
ProUserId = NewType('ProUserId', UserId)
x: ProUserId = ProUserId(UserId(1)) Mypy is happy with that! I will open a new issue about incorrect docs. |
Turns out modern docs already have this problem fixed: https://docs.python.org/3/library/typing.html#newtype |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: