Sunday, November 30, 2014

Re: Python: Assign variable in if statement?


On 2014-11-30, at 12:30 , ThomasTheDjangoFan <stefan.eichholz.berlin@googlemail.com> wrote:

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?

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.

No comments:

Post a Comment