I am trying to figure out the shortest, most pythonic way to implement a similar to the following syntax:
if A and (B if C):
print(A)
in a way that:
- if C is False, then
Bis omitted (therefore(B if C)is True). - if C is True, then B is evaluated, effectively making the syntax
if A and B:
This can be made through various separate if statements, but my ultimate purpose with this was to make it into a list comprehension for a value assignment.
Edit:
The list comprehension I wanted to make was this:
methods = [name for (name, func) in locals().items() \
if callable(func) and (not __name__ == '__main__' or \
func.__module__ == __name__)]
So that it returns the function names I have defined in that module as well as if methods is imported from the outside.
5 Answers 5
This should be equivalent, if my old statement logic doesn't fail me =)
if A and (not C or B):
print(A)
Explanation: "B if C" <=> C -> B <=> not C or B
Expression B is only evaluated if C holds.
Comments
your hypothesis:
- if C is False, then B is omitted
- if C is True, then B is evaluated, effectively making the syntax if A and B:
wouldn't that be:
if A and (not C or B):
print(A)
- if
Cis false thennot CisTrueand we don't evaluateB - if
Cis true, thennot CisFalse, and we have to evaluateB
Comments
Your if pseudo-operator is just logical implication, where
C -> B = not C or B
This means you just want
if A and (not C or B):
When C is False, A and (not C or B) == A and (True or B) == A and True == A.
When C is True, A and (not C or B) == A and (False or B) == A and B.
1 Comment
A && (C -> B) as a Boolean expression instead of A && (!C || B). Whether that is more readable depends on how grounded you are in logic :)This:
if A and (B if C else True):
pass
is closest to your "pseudo code", using the conditional expression x if cond else y in Python. Assuming B=True in case C is False effectively make the if statement consider only the boolean value of A
1 Comment
I'd probably write it like this:
condition = (A and B) if C else A
if condition:
print(A)
I've only broken the condition into a separate variable because I think mixing an if with a Python conditional expression looks a little confusing. You'll have to make a call whether it looks confusing when used inside a list comprehension or not.
if A and (B if C else True):or(A and B) if C else A:A, B = True and C = False -> TrueandA,B,C = True -> Trueright? If so then it would beif A and not C or B: