Member-only story

Today I Learnt — We Can’t Use The Walrus Operator On Attributes??

Liu Zuo Lin
2 min readJul 11, 2024

--

The walrus operator := can condense 2 lines of code into one.

# without walrus operator

x = 'apple'
if x == 'apple':
print('ok')
# with walrus operator

if (x := 'apple') == 'apple':
print('ok')

In (x := 'apple'), 2 things happen that allow this:

  • x is assigned to 'apple'
  • (x := 'apple') itself returns the value 'apple'

Walrus Operator and attributes

But when we try this with object attributes, we get an error.

class Dog:
pass

dog = Dog()

if (dog.age := 5) == 5:
print('ok')

# SyntaxError: cannot use assignment expressions with attribute

So it turns out that we cannot use the walrus operator := on attributes eg. dog.age which is kinda strange to me.

How on earth can we still achieve the same effect in one line of code then?

A workaround

Let’s first deal with setting the attribute

dog.name = 'rocky'
# this is the same as above
setattr(dog, 'name', 'rocky')

# note that setattr() returns None

--

--

Liu Zuo Lin
Liu Zuo Lin

Written by Liu Zuo Lin

SWE @ Meta | [Ebook] 101 Things I Never Knew About Python: https://payhip.com/b/vywcf

Responses (1)