Skip to content

Support NewType #742

@InSyncWithFoo

Description

@InSyncWithFoo

NewType is an almost-zero-runtime-overhead way to create a new subtype:

I64 = NewType('I64', int)
reveal_type(I64)    # Currently: NewType (correct, but lacks information)

takes_i64(42)       # error
takes_i64(I64(42))  # fine

def _(a: I64):
    reveal_type(a)  # I64
    takes_int(a)    # fine

One important thing to note is that I64's type cannot be inferred as type[I64], because at runtime it isn't:

print(I64.__class__)  # 3.10 and later: NewType
                      # 3.9 and older: function

isinstance(42, I64)   # error

Specification: Type aliases § NewType.

Metadata

Metadata

Assignees

Labels

typing semanticstyping-module features, spec compliance, etc

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions