Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python flexible, inline variable assignment

Tags:

python

I'd like to flexibly assign a value to a variable in python, no matter where in my code that variable is.

For instance, given a variable x in an If statement...

if(x == 5):
    print "that's odd."
else:
    print "Woot."

I'd like to be able to assign x right in the if statement like this:

if((x=3) == 5):
    print "that's odd."
else:
    print "Woot."

Is that possible? Here's another example. Let's say I have a line that's:

y = x + 10

I'd like to assign x right there:

y = (x=3) + 10

So I'm looking for a way to find a variable anywhere in my code and give it a value assignment. Is there a pythonic syntax for that?

like image 483
bumpkin Avatar asked Jul 15 '14 06:07

bumpkin


2 Answers

In Python 3.8+, you can use assignment expressions (operator :=):

if (x := 3) == 5:
    print("that's odd")

y = (x := 3) + 10
like image 107
K3---rnc Avatar answered Sep 29 '22 12:09

K3---rnc


"In Python, assignment is a statement, not an expression, and can therefore not be used inside an arbitrary expression. This means that common C idioms like:

while (line = readline(file)) {
    ...do something with line...
}

or

if (match = search(target)) {
    ...do something with match...
}

cannot be used as is in Python. "

http://effbot.org/pyfaq/why-can-t-i-use-an-assignment-in-an-expression.htm

like image 31
osguosgu Avatar answered Sep 29 '22 13:09

osguosgu