Gladiator
Gladiator

Reputation: 644

How to check if a variable is an instance of my custom data type in python?

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

Upvotes: 0

Views: 132

Answers (1)

nickyfot
nickyfot

Reputation: 2019

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

Upvotes: 1

Related Questions