Type comment list of values

123 Views Asked by At

I'm using Jython 2.1, so I cannot use type annotations ({var}: {type}) but I use type comments (# type: {type} for variables and # type: ({param_type}) -> {ret_type} for functions).

I would like to specify that a variable/parameter can only contain specific values, but I don't find any info online.

I tried:

  • variable = "first" # type: "first" | "second": Pylance raises "first" is not defined (same for second)
  • variable = "first" # type: "first|second": Pylance raises "first" is not defined (same for second)
  • variable = "first" # type: first | second: Pylance raises "first" is not defined (same for second)
  • variable = "first" # type: Literal["first", "second"]: Pylance raises "Literal" is not defined (same for second)

I thought of using a try block to make it work only in my environment like this:

try:
    from typing import Literal
except:
    pass

variable = None # type: Literal["first", "second"]

This actually works (Pylance raises Expression of type "None" cannot be assigned to declared type "Literal['first', 'second']"), but also complicates the code that will be deployed in production, potentially leading to bugs caused by name clashing (e.g. what if someone creates a custom typing module which does a completely different thing?)

Is there any way to do it natively, without having to import anything?

0

There are 0 best solutions below