shabda
shabda

Reputation: 1758

If expression variables inside if block

This is a common idiom:

if foo.get("bar"):
    bar = foo.get("bar")
    # DO something with bar

Instead I want to say something like

if foo.get("bar") as bar:
    # DO something with bar

Is there some way to say this in Python?

Upvotes: 2

Views: 72

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1121186

There is no such syntax, no. For dictionaries, you'd usually use a membership test instead:

if 'bar' in foo:
    bar = foo['bar']

This is what most beginning Python programmers think if foo.get('bar') does, but an empty value (e.g. {'bar': 0}) would also be false here.

For the edge case where you really want to skip both missing keys and empty values, you'd use .get() once:

bar = foo.get('bar')
if bar:
    #

The latter could preferable if you are going to store the value in a local variable anyway, but you'd test for is not None to allow for other falsey values:

bar = foo.get('bar')
if bar is not None:
    #

There is no no need to call .get() twice, certainly not when you already determined that the 'bar' key exists.

Upvotes: 2

M4rtini
M4rtini

Reputation: 13539

It's a bit of an hack, but this works.

In [17]: if [bar for bar in [foo.get('bar')] if bar]:
   ....:     print bar

Will not work in python3

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798456

No, there is not.

bar = foo.get('bar')
if bar:
   ...
del bar

Upvotes: 4

Related Questions