Home > Enterprise >  Determining if object is of typing.Literal type
Determining if object is of typing.Literal type

Time:01-19

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:

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

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

CodePudding user response:

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

from typing import _LiteralGenericAlias
if type(GameState) == _LiteralGenericAlias:
     #do something

CodePudding user response:

typing.get_origin() returns Literal for Literal descendandts, so what I needed is basicly

if get_origin(GameState) == Literal:
    # do sth
  •  Tags:  
  • Related