David542
David542

Reputation: 110143

Assignment and addition in one line

Is there an equivalent of the following in python?

ICMP_SEQUENCE_NUM   = self.sequence_num ++

That is, to do assignICMP_SEQUENCE_NUM = self.sequence_num, and after that, increment self.sequence_num by one?

Upvotes: 0

Views: 296

Answers (1)

flakes
flakes

Reputation: 23624

Although there is no way to perform a postfix or prefix operation directly, you can use the new walrus operator := (assignment expression) to get close. This is only possible in Python >= 3.8:

# works
self.sequence_num = (ICMP_SEQUENCE_NUM := self.sequence_num) + 1

Note that you can't use the walrus operator on object attributes, so something like the following is not possible

# does not work
ICMP_SEQUENCE_NUM = (self.sequence_num := self.sequence_num + 1) - 1

Upvotes: 3

Related Questions