Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Typed NamedTuple with member function generating another instance of class fails at runtime with NameError #485

Closed
lwolfsonkin opened this issue Oct 19, 2017 · 7 comments

Comments

@lwolfsonkin
Copy link

I simplified the code just for proof of concept:

class Hypothesis(NamedTuple):
    logprob: float
    def attach(self) -> Hypothesis:
        return Hypothesis(logprob=4)

While mypy doesn't complain at this, the python interpreter crashes with a NameError saying:

Traceback (most recent call last):
  File "./decode.py", line 31, in <module>
    class Hypothesis(NamedTuple):
  File "./decode.py", line 34, in Hypothesis
    def attach(self) -> Hypothesis:
NameError: name 'Hypothesis' is not defined

Unfortunately, I dropped the return type annotation as a result (which mypy didn't complain about) in order to make it runnable.

@ethanhs
Copy link
Contributor

ethanhs commented Oct 20, 2017

This is because the name Hyposthesis is not defined inside its own class definition body. Mypy accepts this due to supporting this in stubs being needed. You can change the return annotation to be -> 'Hypothesis' and it will both work at runtime and be understood by mypy.

@lwolfsonkin
Copy link
Author

Thanks for the tip! Interesting. So, the name Hypothesis is not defined in the class body, but is defined in methods within that class body?

@ethanhs
Copy link
Contributor

ethanhs commented Oct 20, 2017

Methods are part of the class body. So this also will not work

class Example:
    def test(a: Example):
        pass

nor this

class Example:
    def test(a) -> Example:
        pass

However, the same use of quotes can be used.

@lwolfsonkin
Copy link
Author

huh. Cool. Definitely good to know. Thanks a lot @ethanhs!

@gvanrossum
Copy link
Member

I do think there's a mypy bug here -- outside stubs, this should be rejected.

@JukkaL
Copy link
Contributor

JukkaL commented Oct 20, 2017

I do think there's a mypy bug here -- outside stubs, this should be rejected.

Yes, and we already have a mypy issue about this (python/mypy#948).

@ilevkivskyi
Copy link
Member

@gvanrossum

I do think there's a mypy bug here -- outside stubs, this should be rejected.

...or PEP 563 can be accepted :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants