Conditional with statement in Python
If you want to avoid duplicating code and are using a version of Python prior to 3.7 (when contextlib.nullcontext
was introduced) or even 3.3 (when contextlib.ExitStack
was introduced), you could do something like:
class dummy_context_mgr():
def __enter__(self):
return None
def __exit__(self, exc_type, exc_value, traceback):
return False
or:import contextlib
@contextlib.contextmanager
def dummy_context_mgr():
yield None
and then use it as:with get_stuff() if needs_with() else dummy_context_mgr() as gs:
# do stuff involving gs or not
You alternatively could make get_stuff()
return different things based on needs_with()
.(See Mike's answer or Daniel's answer for what you can do in later versions.)
Using a conditional 'with' statement in Python
The cleanest solution is probably to define ds
beforehand:
if sourceRef:
ds = open(sourceRef, 'rb')
else:
ds = self._validate(source)
with ds:
dstreams['master'] = self._generateMasterFile(ds)
This approach also works in a clean way when you have more than two possible ds
values (you can simply extend the checks beforehand to determine the value for ds
). Conditional or optional context managers in with statement
Here's an easy way to wrap around an existing context manager without even using any classes:
from contextlib import contextmanager
@contextmanager
def example_context_manager():
print('before')
yield
print('after')
@contextmanager
def optional(condition, context_manager):
if condition:
with context_manager:
yield
else:
yield
with example_context_manager():
print(1)
with optional(True, example_context_manager()):
print(2)
with optional(False, example_context_manager()):
print(3)
Output:before
1
after
before
2
after
3
How to make a conditional If statement that has to only meet a percentage of its conditions in Python?
Edit: as pointed out by u/schwobaseggl, you don't even need the conversion to int
:
if sum([a > b, a < c, a == d]) >= 2:
print("Conditions have been met")
if sum(map(int, [a > b, a < c, a == d])) >= 2:
print("Conditions have been met")
This creates a boolean list with the result of each of the values, then converts them all to 1
if they're True
, or 0
if False
, then sums up the whole list, giving you the number of True conditions.Note that this won't short-circuit, aka it will still evaluate all the conditions even if there are enough True
ones in the first part of the list to ignore the rest.
Does Python have a ternary conditional operator?
Yes, it was added in version 2.5. The expression syntax is:
a if condition else b
First condition
is evaluated, then exactly one of either a
or b
is evaluated and returned based on the Boolean value of condition
. If condition
evaluates to True
, then a
is evaluated and returned but b
is ignored, or else when b
is evaluated and returned but a
is ignored.This allows short-circuiting because when condition
is true only a
is evaluated and b
is not evaluated at all, but when condition
is false only b
is evaluated and a
is not evaluated at all.
For example:
>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'
Note that conditionals are an expression, not a statement. This means you can't use statements such as pass
, or assignments with =
(or "augmented" assignments like +=
), within a conditional expression:>>> pass if False else pass
File "<stdin>", line 1
pass if False else pass
^
SyntaxError: invalid syntax
>>> # Python parses this as `x = (1 if False else y) = 2`
>>> # The `(1 if False else x)` part is actually valid, but
>>> # it can't be on the left-hand side of `=`.
>>> x = 1 if False else y = 2
File "<stdin>", line 1
SyntaxError: cannot assign to conditional expression
>>> # If we parenthesize it instead...
>>> (x = 1) if False else (y = 2)
File "<stdin>", line 1
(x = 1) if False else (y = 2)
^
SyntaxError: invalid syntax
(In 3.8 and above, the :=
"walrus" operator allows simple assignment of values as an expression, which is then compatible with this syntax. But please don't write code like that; it will quickly become very difficult to understand.)Similarly, because it is an expression, the else
part is mandatory:
# Invalid syntax: we didn't specify what the value should be if the
# condition isn't met. It doesn't matter if we can verify that
# ahead of time.
a if True
You can, however, use conditional expressions to assign a variable like so:x = a if True else b
Or for example to return a value:# Of course we should just use the standard library `max`;
# this is just for demonstration purposes.
def my_max(a, b):
return a if a > b else b
Think of the conditional expression as switching between two values. We can use it when we are in a 'one value or another' situation, where we will do the same thing with the result, regardless of whether the condition is met. We use the expression to compute the value, and then do something with it. If you need to do something different depending on the condition, then use a normal if
statement instead.Keep in mind that it's frowned upon by some Pythonistas for several reasons:
- The order of the arguments is different from those of the classic
condition ? a : b
ternary operator from many other languages (such as C, C++, Go, Perl, Ruby, Java, JavaScript, etc.), which may lead to bugs when people unfamiliar with Python's "surprising" behaviour use it (they may reverse the argument order). - Some find it "unwieldy", since it goes contrary to the normal flow of thought (thinking of the condition first and then the effects).
- Stylistic reasons. (Although the 'inline
if
' can be really useful, and make your script more concise, it really does complicate your code)
x = 4 if b > 8 else 9
is read aloud as x will be 4 if b is greater than 8 otherwise 9
.Official documentation:
- Conditional expressions
- Is there an equivalent of C’s ”?:” ternary operator?
How to add a conditional statement as an argument to a function in python?
You can pass the condition as a string which you then evaluate within your function. For example:
def func(condition, count):
while eval(condition):
count += 1
return count
print(func('count < 3', 0))
Output:3
Python conditional statements
Note that
a&b&c >= 2
is different from a>=2 and b>=2 and c>=2.
I think you mean the second one, i.e. all values are larger than two. (The first one does a binary and with all your values and compares this to the value two.)
Related Topics
Use Index in Pandas to Plot Data
Continuing in Python's Unittest When an Assertion Fails
Get the String Within Brackets in Python
Stop Matplotlib Repeating Labels in Legend
Suppressing Scientific Notation in Pandas
Why Does the Floating-Point Value of 4*0.1 Look Nice in Python 3 But 3*0.1 Doesn'T
Python Using Variables from Another File
Use Scikit-Learn to Classify into Multiple Categories
Pandas Dataframe Column to List
Importerror: Cannot Import Name Numpy_Mkl
How to Print a Dictionary Line by Line in Python
Python and Operator on Two Boolean Lists - How
How to Set Opacity of Background Colour of Graph with Matplotlib
Safely Create a File If and Only If It Does Not Exist with Python