Python: Assign variable in if statement?

201 views
Skip to first unread message

ThomasTheDjangoFan

unread,
Nov 30, 2014, 6:30:17 AM11/30/14
to django...@googlegroups.com
Hi guys,

coming from php I am wondering if there is a way to do something like this in Python/Django:

if variable = get_a_value_from_function():
  new_stuff
= variable

Of course I can use

variable = get_a_value_from_function()
if variable:
  new_stuff
= variable

But is there a shortcut similar to php?

Kind regards
Thomas

Marc Aymerich

unread,
Nov 30, 2014, 10:24:25 AM11/30/14
to django-users
perhaps something like:

new_stuff = get_a_value_from_function() or get_a_value_from_other_function()


--
Marc

Masklinn

unread,
Nov 30, 2014, 11:23:22 AM11/30/14
to django...@googlegroups.com
Not as such. Python intentionally didn't include assignment within
statements (mostly conditionals) to avoid the common issue of
assignments-instead-of-equality bugs.

If `new_stuff` has a default value, you could always write.

    new_stuff = some_function() or new_stuff

which will reassign `new_stuff` to itself if `some_function()` returns a
falsy value. If you need a more complex conditional body than just an
assignment, you'll need the long one.

Derek

unread,
Dec 4, 2014, 1:59:45 AM12/4/14
to django...@googlegroups.com, mask...@masklinn.net
Or, if new_stuff does not already exist, and you want to create a fallback/default value for it, you could use:

    new_stuff = some_function() or "foo"

Reply all
Reply to author
Forward
0 new messages