0

I want to do a type check of a variable against my custom variable. How to achieve something like below,

Predicate = Tuple[str, str , str]
LogicalPredicate = Tuple[Predicate, str, Predicate]
my_var = ('age', 'is', 'null')
if isinstance(my_var, Predicate):
  #do something
else if isinstance(my_var, LogicalPredicate):
  #do something else
else:
  raise ValueError

1 Answer 1

1

Typing library is mainly used for type hints and improving readability, so the syntax Tuple[str, str, str] is a class meta rather than a type. To check if my_var has the right format with isinstance you need a slightly different syntax:

Predicate = type(('','',''))
LogicalPredicate = type((Predicate, '', Predicate))

This then should work with isinstance()

EDIT

As kindly pointed out, the above returns True for all Tuple instances; to check the elements within the Tuple one more step is required to test Predicate:

tuple(map(type, my_var)) == (str, str, str)

to check logical predicate more conditions need to be added (so worth considering converting this to a method) but overall:

my_var = ('age', 'is', 'null')
if isinstance(my_var, tuple) and  tuple(map(type, my_var)) == (str, str, str):
    print('Predicate')
elif isinstance(my_var, tuple) and tuple(map(type, my_var[0])) == (str, str, str) and tuple(map(type, my_var[2])) == (str, str, str) and isinstance(my_var[1], str):
    print('LogicalPredicate')
else:
    raise ValueError

Similar explanations can be found on this question

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @nickthefreak for responsing. I tried running the code, but the isinstance() passed True even if myvar did not follow the format ('','','').
interesting! I think the issue is that it's True as long as it is a tuple. Let me research more and come back with a correction (or deletion of the answer)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.