Reputation: 1782
The Python documentation shows use of NewType like this:
import typing
foo = typing.NewType('foo', int)
some_id = foo(524313)
I don't understand exactly what the syntax is doing. How does that differ from this:
import typing
bar = typing.NewType('foo', int)
some_id = bar(524313)
What are the consequences of 'foo' != 'bar' in the source above?
Or, maybe worse:
import typing
bar = typing.NewType('foo', int)
some_id = foo(524313)
Upvotes: 1
Views: 436
Reputation: 54698
Two different purposes. The parameter to NewType is used to describe the type for diagnostic purposes, like error messages. It can't know what name you actually stored the type in. The return value is the actual class object. Mixing them, while possible, will generally result in tears.
Your third example will fail because there is no foo
.
The idea is that, later, you can enforce type checking:
some_id : foo = bar(524313)
That triggers a diagnostic.
Upvotes: 2