This question already has answers here:
Python Ternary Operator Without else
(8 answers)
Conditional return with no else
(2 answers)
Closed last month.
Quite frequently, I have written lines like
if arg == foo: return bar
It is naturally a one-liner, at the beginning of a function body. Notice there is no else, it just returns on a special value of the parameter, and proceeds with the normal flow of the function otherwise.
Still, it feels like the order is wrong. In perl it is possible to write (modulo some $'s)
return bar if arg == foo
which feels more natural. Matter of taste, I know.
Is there a pythonic way of writing something after a return word that would impose a condition on the return statement?
It is, of course, possible, that there is no way.
Related
This question already has answers here:
Python: avoiding if condition for this code?
(8 answers)
What does colon equal (:=) in Python mean?
(6 answers)
Closed 27 days ago.
Let's say we have the following code:
if re.search(r"b.", "foobar"):
return re.search(r"b.", "foobar").group(0)
This is obviously a redundant call, which can be avoided by assigning the condition to a variable before the if block:
match = re.search(r"b.", "foobar")
if match:
return match.group(0)
However, this means that the condition is always evaluated. In the example above, that makes no difference, but if the match is only used in an elif block, that's an unnecessary execution.
For example:
match = re.search(r"b.", "foobar")
if somecondition:
return "lorem ipsum"
elif match:
return match.group(0)
If somecondition is true and we had the redundant version like in the first code block, we would never call re.search. However, with the variable placed before the if-elif-Block like this, it would be called unnecessarily. And even with the duplicated call, we're instead executing it twice if somecondition is false.
Unfortunately, depending on the use case, evaluating the condition could be very computationally expensive. With the two variants above, if performance is the goal, a choice can be made depending on the likelyhood of somecondition evaluating to true. More specifically, if the elif block is called more often than not, declaring the variable before if the if block is more performant (unless Python somehow caches the result of two identical stateless function calls), whereas the alternative is better if the elif block is rarely reached.
Is there a way to avoid this duplication by reusing the variable from the (el)if block?
This question already has answers here:
if x:, vs if x == True, vs if x is True
(8 answers)
Closed 2 years ago.
When making an 'if' statement in Python, we have the option to use if boolean:, without making an explicit comparison (which is not mandatory)
The question is: what is the default comparison in this case? Is if x: equivalent to if x == True or if x is True?
Not sure if I understand your question, but you can use:
if True:
print("hi")
which will return "hi" once
If you're looking to make an infinite loop, try something like this:
while True:
#do whatever here and it will loop infinitely
This question already has answers here:
If and elif in Python for good programming practices
(2 answers)
Closed 4 years ago.
Does someone have a simple answer as to why you would use a If If rather than an If Elif?
Example:
def fun(item):
if item[0]<'M':
return 0
if item[0]<'Q':
return 1
return 2
With a setup like this, where you are returning a value inside each if block, the if statements behave exactly the same as an if elif structure since the return exits out of the function without checking the conditions below. So, when the functionality is the same, the choice should be made on readability. explicit is better than implicit.
There is no good reason to use if statements like this implying exclusively in the conditionals, when if elif statements makes the exclusivity explicit and is much more readable and easier to maintain.
This question already has answers here:
Using pass on a non necessary else statement
(5 answers)
Closed 8 years ago.
Is there a preferred/proper style?
This:
def fx(Boolean):
if Boolean:
# Do stuff.
else:
pass
Or this:
def fx(Boolean):
if Boolean:
# Do stuff.
Is it preferred/proper to include else: pass if you don't want anything to happen?
I've read PEP 8 - Style Guide for Python Code and did not find anything concerning my question.
You should never include else: pass. It's superfluous. Just omit the else; it's intentionally an optional keyword.
If you don't need the else if there is no reason to add it. It will just confuse other people reading your code in the future (ie yourself a few months later).
This question already has answers here:
Creating functions (or lambdas) in a loop (or comprehension)
(6 answers)
Closed 8 years ago.
when working with python, it bothered me that while obj.method() is perfectly fine, method(obj) isn't allowed. So I figured I'd try to write some code to fix that. I came up with the next:
def globalclassfuncs(defobj):
for i in inspect.getmembers(defobj, predicate=inspect.ismethod):
def scope():
var = i[0];
setattr(sys.modules[__name__], i[0], lambda obj, *args: getattr(obj, var)(*args));
scope();
However, there's something weird with this. When I remove def scope(): and scope(), so that it'll run without a function definition in the for loop, or when I change the getattr() function to use i[0] directly instead of through var, somehow all new defined functions point to the last defined function instead of the function they should point to. Why does this behaviour change so much on such small changes in the code?
Seems like a case of late binding closure