Add NewType() to create simple unique types with zero runtime overhead #189
|
I think this is a useful feature. I have added PR #226 with a simple minded implementation of Also I added I do not discuss whether |
|
I would like to limit the arg to a class. Also note that that class must have a constructor that is compatible with that assumed by the type checker -- because whenever you write
UPDATE: As pointed out below this is backwards. In order not to confuse future readers I'm not changing my words but adding this disclaimer. |
OK
Actually, at runtime, |
|
I guess you need to clarify this -- using int or str as examples doesn't make this clear at all, since they have the same signature. (And sorry for having such a frazzled memory that I didn't remember this -- but maybe it's been helpful teasing out the ambiguities in the description. :-) FWIW I think we should take this to python-dev for a formal review period. |
OK, I will do this and then will post a link to the PR to python-dev. |
|
To summarize, the essence here is that to the type checker, UserId is a subclass of int with a constructor that takes an int, while at runtime it is the identity function that returns its argument (hopefully an int :-) unchanged. (ADDED:) From this it follows that e.g. adding 1 to a UserId instance is legal and produces an int, not a UserId. |
I totally agree with this, there is already this example in the text |
|
I just wrote that down to summarize the proposal in the fewest words possible (and because I had never quite realized before that this is how the proposal works out -- it's a very sweet proposal that can be summarized so briefly). |
|
The PEP text landed (PR #226). I'd really like to get the typing.py changes in too! |
|
NM, the typing.py changes landed too: 807d3a9. |
The description is best gleaned from the following mypy issue: python/mypy#1284 (comment) and following. We're going with option (A).
Really brief example:
Now to the type checker UserId is a new type that's compatible with int, but converting an int to a UserId requires a special cast form, UserId(x). At runtime UserId instances are just ints (not a subclass!) and UserId() is a dummy function that just returns its argument.