0

After searching for the reason of a NameError in my script for way too long, I realized that I mistyped = as : on the related assignment, i.e.:

In [1]: a: 1
In [2]: # ...
In [3]: a += 1
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-3-3a23b85b51e9> in <module>()
----> 1 a += 1
NameError: name 'a' is not defined

What I find curious about this is that the syntax var: expression neither seems to do anything nor throws an error. This appears to work in IPython or a local console for python 3 In python 2 the syntax gives an error!

Any hints as to what happens here?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
mrclng
  • 483
  • 2
  • 14
  • It's a [type hint](https://docs.python.org/3/library/typing.html). – a_guest Jan 22 '19 at 18:10
  • It *might* be a type hint, which is just one use case for a *variable annotation*, which is what this is. – chepner Jan 22 '19 at 18:31
  • Alright, I'll look into this! But why does type hinting work with literals? Is that syntax equivalent to `a: int`? – mrclng Jan 22 '19 at 18:35
  • @mrclng Python itself doesn't care *what* that annotation is, as long as it is a valid Python expression. External tools like `mypy` are what *interpret* the value as a type for type checking. – chepner Jan 22 '19 at 18:36
  • (It's somewhat unfortunate that an annotation alone can suppress the `NameError` you would have gotten from `a` alone, but I think it's the result of the *intention* that the annotation be used as a type hint.) – chepner Jan 22 '19 at 18:39
  • Hmm I see... So should I close this question or keep it so people that come across the same issue as I did can find it? – mrclng Jan 22 '19 at 18:41

0 Answers0