Skip to content Skip to sidebar Skip to footer

Python Flexible, Inline Variable Assignment

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): pri

Solution 1:

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

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

y = (x := 3) + 10

Solution 2:

"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

Solution 3:

globals().setitem('a',1) or a

this is a bit hacky, but 2 things are possible, declare/assign a variable through the locals() or globals() function. use or to chain an inplace function (that returns None).

i doubt using either of those is consider a good practice, but they are available

Solution 4:

Python doesn't support Inline assignment. Why? Because everything is an object, and objects should be callable. Example:

This is not possible is python if ((x=10) > 20):

Here we are assigning x as an instance of the Int class and executing it in the if expression.

Although such a statement is possible in C/C++ because it's build with a different mindset.

Post a Comment for "Python Flexible, Inline Variable Assignment"