How can a check for list membership be inverted based on a boolean variable?
I am looking for a way to simplify the following code:
# variables: `is_allowed:boolean`, `action:string` and `allowed_actions:list of strings`
if is_allowed:
if action not in allowed_actions:
print(r'{action} must be allowed!')
else:
if action in allowed_actions:
print(r'{action} must NOT be allowed!')
I feel there must be a way to avoid doing the check twice, once for in
and another time for not in
, but can't figure out a less verbose way.
Compare the result of the test to is_allowed
. Then use is_allowed
to put together the correct error message.
if (action in allowed_actions) != is_allowed:
print(action, "must" if is_allowed else "must NOT", "be allowed!")