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

Determining if object is of typing.Literal type

I need to check if object is descendant of typing.Literal, I have annotation like this:

GameState: Literal['start', 'stop']

And I need to check GameState annotation type:

def parse_values(ann)
   if isinstance(ann, str):
       # do sth
   if isinstance(ann, int):
       # do sth
   if isinstance(ann, Literal):
       # do sth

But it causes error, so I swapped the last one to:

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

if type(ann) == Literal:
   # do sth

But it never returns True, so anyone knows a workaround for this?

>Solution :

you should compare with <class 'typing._LiteralGenericAlias'> instead:

from typing import _LiteralGenericAlias
if type(GameState) == _LiteralGenericAlias:
     #do something
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