2

I have this code:

str = func(parameter)
if not str:
   do something.

the function func() return a string on success and '' on failure. The do something should happen only if str actualy contain a string.

Is it possible to do the assigmnt to str on the IF statment itself?

2
  • you should define that inside the function func. Commented Sep 28, 2016 at 6:27
  • Possibly a duplicate of "[stackoverflow.com/q/8826521/90527](Python: avoiding if condition for this code?)" (though this question is more focused on the general problem, rather than on specific code, and is thus a better expression of the issue). Commented May 2, 2022 at 1:30

5 Answers 5

2

In one word: no. In Python assignment is a statement, not an expression.

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

Comments

1

Why not try it yourself,

if not (a = some_func()):
  do something
      ^
SyntaxError: invalid syntax

So, no.

Comments

1

PEP 572 added syntax for assignment expressions. Specifically, using := (called the "walrus operator") for assignment is an expression, and thus can be used in if conditions.

if not (thing := findThing(name)):
    thing = createThing(name, *otherArgs)

Note that := is easy to abuse. If the condition is anything more complex than a direct test (i.e. if value := expresion:) or a not applied to the assignment result (such as in the 1st sample above), it's likely more readable to write the assignment on a separate line.

Comments

0

With the below code snippet, if the func returns a string of length > 0 only then the do something part will happen

str = func(parameter)
if str:
   do something

Comments

0

You can try this, it's the shortest version I could come up with:

if func(parameter):
   do something.

Comments

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.