0

I have a function that prints names of the all possible options in the enumeration.

When I run the mypy for my code it gives: error: Need type annotation for 'item' [var-annotated]

Here is my code:

import enum

def function(enumeration: enum.EnumMeta) -> None:
    options = (item.name for item in enumeration)
    print(f"Valid options are: {', '.join(options)}")

I don't want to ignore it or use the normal for loop. Is there any way to annotate it?

EDIT:

I have already tried the below methods:

item: TypeOfItem
options = (item.name for item in enumeration)

and

from typing import cast
options = (cast(TypeOfItem, item).name for item in enumeration)
ErdoganOnal
  • 800
  • 6
  • 13
  • Afaik, you can't easily or cleanly. putting `item: the_type` on the line above *may* work, although I'm not sure since comprehensions have their own scope. – Carcigenicate May 06 '21 at 13:58
  • At least in Pycharm, "pre-annotating` on the line above works. Pycharm uses a different linter though, so idk if that's compatible with mypy. – Carcigenicate May 06 '21 at 13:59
  • Does this answer your question? [How do I annotate types in a for-loop](https://stackoverflow.com/questions/41641449/how-do-i-annotate-types-in-a-for-loop). Potentially? Try it out. – Carcigenicate May 06 '21 at 14:00
  • I have already tried it but no chance... – ErdoganOnal May 06 '21 at 14:00
  • 1
    Since you're writing a generator expression, it's evaluated in its own stack frame and `item` is local to that - it's not the same variable as the `item` you declare above it. So an annotation outside the generator can't work. – kaya3 May 06 '21 at 14:12
  • You could cast enumeration instead of item. – hussic May 11 '21 at 09:42

0 Answers0