Currently NewType has a rather unsatisfactory repr:
from typing import NewType
A = NewType("A", int)
print(repr(A))
outputs:
<function NewType.<locals>.new_type at MEMORYADDRESS>
This (1) doesn't refer to the name of the NewType, (2) doesn't refer to the wrapped type, (3) doesn't refer to the module the NewType was defined in, and (4) is confusing.
If a function is defined with the NewType in its signature, this repr appears in inspect.getsignature(signature_of_function).
For example:
from typing import NewType
A = NewType("A", int)
def test(a : A):
pass
import inspect
sig = inspect.signature(test)
annotation = list(sig.parameters.values())[0].annotation
print(inspect.formatannotation(annotation))
prints
<function NewType.<locals>.new_type at MEMORYADDRESS>
This shows up in Jedi output:
from typing import NewType
A = NewType("A", int)
def test(a : A):
pass
import jedi
test_jedi = jedi.Interpreter("test", [globals()]).complete()[0]
print(test_jedi.docstring())
prints
test(a: <function NewType.<locals>.new_type at MEMORYADDRESS>)
Presumably you could fix this by turning NewType into a class:
class NewType:
def __init__(self, name, tp):
self.__name__ = name
self.__supertype__ = tp
def __call__(self, x):
return x
def __repr__(self):
return self.__name__
This change would also make it less opaque how to test whether an object is a NewType (I think currently the best way to make this check is to say hasattr(x, "__qualname__") and x.__qualname__ == 'NewType.<locals>.new_type' which is not exactly transparent.
I imagine this change could break typecheckers which are likely to care about the implementation details of NewType, but the fix for the type checkers shouldn't be too complicated.
Currently
NewTypehas a rather unsatisfactoryrepr:outputs:
This (1) doesn't refer to the name of the
NewType, (2) doesn't refer to the wrapped type, (3) doesn't refer to the module theNewTypewas defined in, and (4) is confusing.If a function is defined with the
NewTypein its signature, this repr appears ininspect.getsignature(signature_of_function).For example:
prints
This shows up in Jedi output:
prints
Presumably you could fix this by turning
NewTypeinto a class:This change would also make it less opaque how to test whether an object is a NewType (I think currently the best way to make this check is to say
hasattr(x, "__qualname__") and x.__qualname__ == 'NewType.<locals>.new_type'which is not exactly transparent.I imagine this change could break typecheckers which are likely to care about the implementation details of
NewType, but the fix for the type checkers shouldn't be too complicated.