Mypy: NewType/NamedTuple local inferred to be `Any` if type defined after function.

Created on 21 Aug 2018  Â·  2Comments  Â·  Source: python/mypy

  • Minimal repro:
from typing import NewType


def before() -> None:
    bar = Bar(10)
    annotated_bar = Bar(10)  # type: Bar

    reveal_type(bar)  # Revealed type is 'Any'
    reveal_type(annotated_bar)  # Revealed type is 'x.Bar'


Bar = NewType('Bar', int)


def after() -> None:
    bar = Bar(10)
    reveal_type(bar)  # Revealed type is 'x.Bar'
  • What is the actual behavior/output?
    The type of bar inside before is inferred as Any.

  • What is the behavior/output you expect?
    The type of bar inside before should be inferred as Bar, the NewType.

  • What are the versions of mypy and Python you are using?

(env-rw) fl•~/r/rw(dis⚡)» pip freeze | rg mypy
mypy==0.620
(env-rw) fl•~/r/rw(dis⚡)» python -V
Python 3.6.5

Issue is still present on master:

(env-rw) fl•~/r/rw(dis⚡)» pip install git+git://github.com/python/mypy.git
[...snip...]
(env-rw) fl•~/r» pip freeze | rg mypy
mypy==0.630+dev.402d734c4b8ceffdc04478eb49fc196dd2a3a785
(env-rw) fl•~/r» mypy  x.py
x.py:8: error: Revealed type is 'Any'
x.py:9: error: Revealed type is 'x.Bar'
x.py:17: error: Revealed type is 'x.Bar'
bug priority-2-low

All 2 comments

Thanks for reporting!

We have seen similar bugs previously, but this one is a false negative and there is a simple workaround (move definition before the function), so this is probably a relatively low priority.

Thanks for the quick reply! That makes sense, I was surprised that the order affected things at all, so I thought it might be a useful datapoint for maintainers.

For me the bigger problem was that it was silently inferred to be Any (even with --strict) and masked a bug, rather than something like a no such type 'Bar' error. I take your point about relative priority of false negatives, though.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

tjltjl picture tjltjl  Â·  35Comments

JukkaL picture JukkaL  Â·  28Comments

MarkCBell picture MarkCBell  Â·  25Comments

JukkaL picture JukkaL  Â·  30Comments

JukkaL picture JukkaL  Â·  27Comments