0

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.

3
  • 1
    Do testing twice for readability sake. Commented May 18, 2021 at 7:20
  • Is it always a list of instances or a list of classes? Or can it be a heterogeneous list of instances mixed with classes? Commented May 18, 2021 at 7:21
  • Hi, @deeze: It is homogenous, either only values or only types. At pavel: I will consider this :-) Commented May 18, 2021 at 7:27

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

7 Comments

Great and readable solution for the homogeneous case, thanks a lot. I was not considering using isinstance together with a "tuplization".
One, however, should test the "variable in value_choices" part first, otherwise, for values/instances, the isinstance part results in a TypeError: isinstance() arg 2 must be a type or tuple of types.
Uhm, no…?! If class_choices is actually a non-empty sequence of classes, then it doesn't matter what order you do the test in. If the list may be empty of course, you need to revise…
I see my error. You separated class_choices from value_choices, but I cannot tell whether it is classes/types or values. It might be either. Homogenous, but either.
Then you should make your internal logic clearer if possible…
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.