gilgamash
gilgamash

Reputation: 902

Testing a variable for type or instance/value

I want to check whether a variable is in a set of allowed choices. The choices may be values such as

choices = ['a', 'b', 4, 6]

but also be classes or types such as

choices = [int, MyClassA, MyClassB]

I use simply check via

variable in choices

and want to avoid implementing the same test twice, once for values and once, if that fails, for types.

EDIT: When the program performs the test it does NOT know in advance whether choices is a list of values or types/classes. The list themselves however are homogenous and strictly of one kind or the other.

Upvotes: 0

Views: 63

Answers (1)

deceze
deceze

Reputation: 522626

If it's a heterogenous mix of instances ("values") and classes, then you need to do something like:

any(isinstance(variable, i) if isinstance(i, type) else variable == i for i in choices)

That is of course very unreadable. If you have separate lists of classes and values, that check can be made a lot more readable:

isinstance(variable, tuple(class_choices)) or variable in value_choices

Upvotes: 3

Related Questions