Can Python instantiate a variable and return its value or reference at the same time?

Viewed 41

Can Python instantiate a variable and return its value or reference at the same time?

Something that would work like this

fruits = list()
fruits.append(apple = Fruit()) # (apple = Fruit()) <= Would return a reference/value
fruits.append(orange = Fruit())

apple.do_something()
fruits[1].do_something()

Obviously, you could just access objects with fruits[n], but can Python do this? Why?

1 Answers

As of 3.8, yes, using the "walrus operator", := (officially called an "assignment expression"):

fruits = list()
fruits.append(apple := Fruit())
fruits.append(orange := Fruit())

apple.do_something()
fruits[1].do_something()

:= allows assignment as an expression, rather than a statement, and the expression evaluates to the thing assigned.

Prior to 3.8 this was not possible; you'd have to split it up. The least verbose modification to your existing code would be something like:

fruits = list()
fruits.append(Fruit())
fruits.append(Fruit())
apple, orange = fruits   # Unpacks list to multiple names all at once

or store to names and build the list:

apple = Fruit()
orange = Fruit()
fruits = [apple, orange]
Related