Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

repr of NewType #746

Copy link
Copy link
@hoodmane

Description

@hoodmane
Issue body actions

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.

Reactions are currently unavailable

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.