Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pylance: Argument of type "int" cannot be assigned to parameter of type "Literal[24, 48]"

from typing import Literal

def predict(window: Literal[24, 48]):
    pass

for window in [24, 48]:
    predict(window=window)

Let’s say I have the above code. I’m trying to type annotate my code. However Pylance says it’s incorrect:

Argument of type "int" cannot be assigned to parameter "prediction_range" of type "Literal[24, 48, 168]" in function "predictor"
Type "int" cannot be assigned to type "Literal[24, 48]"
"int" cannot be assigned to type "Literal[24]"
"int" cannot be assigned to type "Literal[48]"

I don’t understand why the int 24 cannot be assigned to Literal int with the same value. What is the correct way to annotate this code?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

[24, 48] is deduced as list[int]. The information about specific values is lost.

If you want to specify a different type, you can:

from typing import Literal

def predict(window: Literal[24, 48]):
    pass

windows: list[Literal[24, 48]] = [24, 48]

for window in windows:
    predict(window=window)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading