2

I have the simple Python 3 expression:

if a:
    b = a
else:
    print('error')

However in my case, it just so happens that 'a' is equal to a very verbose but necessary regex search command (not relevant here.) Can I simplify the above code so that:

1) I don't need to assign a value to 'a'.

2) I don't need to state the value of 'a' twice in the expression.

Thanks!

2

2 Answers 2

3

In Python 3.8, named assignments will be introduced that let you do:

if a := complicated_expression: 
    b = a

The suggestion

b = a or b

is valid, but requires that b is assigned a value beforehand. Also it just works if the condition only checks for the truthiness of a For a strict one-liner with an arbitrary condition, you can always use the singleton generator-trick:

b = next((a for a in (complex_expression for _ in '_') if condition(a)), None)

But that should be considered purely academical.

Sign up to request clarification or add additional context in comments.

3 Comments

But even then, you're assigning to a temporary variable. := just saves a line.
@RemcoGerlich That's true, but the asumption is that this line is what the OP wants to save.
Thanks for this - great answer but unfortunately not usable currently
1

You can do:

b = a or False
if b:
    print("okay")
else:
    print("error")

where False can be any special value you can set yourself that can be used as a default value for b if a is falsy (provided that the condition of the if changes if the default value changes).

>>> import re
>>> 
>>> def check(rgx, s):
>>>   b = re.search(rgx, s) or False
>>>   if b:
>>>     print("okay")
>>>     return b
>>>   else:
>>>     print("error")
>>> 
>>> check('\W', 'Hello, world!')
okay
<re.Match object; span=(5, 6), match=','>
>>> check('\d', 'Hello, world!')
error

5 Comments

I think it should be 'or b', to keep the old value of b.
@RemcoGerlich won't b = a or b raise a NameError for the b in the RHS?
This answer is great for my original question but I neglected to mention I want to keep it in an 'if statement' format, so that I can use the 'else' functionality to raise an error. Sorry - have made an edit
@freddieaj In this case, you can use your if with b.
@MrGeek: I was assuming that b already had a value, otherwise his if statement would lead to the situation that further on, b would either have a value or be a NameError, and that would be bad. But he planned on using else:, so maybe it didn't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.