ban
ban

Reputation: 197

Python - assign value and check condition in IF statment

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?

Upvotes: 2

Views: 311

Answers (5)

outis
outis

Reputation: 77400

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.

Upvotes: 1

bruno desthuilliers
bruno desthuilliers

Reputation: 77892

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

Upvotes: 2

user3543300
user3543300

Reputation: 507

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

if func(parameter):
   do something.

Upvotes: 0

Gopi Vinod Avvari
Gopi Vinod Avvari

Reputation: 294

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

Upvotes: 0

Net Myth
Net Myth

Reputation: 461

Why not try it yourself,

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

So, no.

Upvotes: 1

Related Questions