No error / no effect for "a: 1"

The aforementioned code

a: 1

throws no error and has no effect. (To me, it looks like type annotation of a).
This is in contrast to

a

which throws

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

Is this intended behavior?

In my more complex use case, this feature overshadowed a typing error (: instead of =). Our code, which had no effect, was something like:

my_dict['very_long_dict_key']: [
    <complex array content>
]

Arno

Yes this is intended. Relevant part of the grammar:

assignment:
    | NAME ':' expression ['=' annotated_rhs ] 

1 is a valid expression so it matches this rule. Note that the assignment is optional indicated by square brackets. I don’t know if there are any linters that catch this but most type checkers would warn you that this annotation with a literal is not expected.

That’s exactly what it is. Using 1 as a type annotation doesn’t mean much, but if you instead wrote:

a: int

then this would be a completely valid and meaningful annotation.

When you say a: int = 1, you are both annotating and assigning. When you say a: int you are just annotating. But when you say just a on its own, that’s querying. Yes, it’s a little odd, but there’s no way around this; you can think of this in the same way as a C-like language could have a variable declaration without an initializer [1] - it is waiting for the assignment that should follow.


  1. granted, a lot of high-level C-like languages have an implicit initializer in this situation, but we’ll ignore that ↩︎