Falmarri
Falmarri

Reputation: 48577

Python variable assignment order of operations

Is there a way to do a variable assignment inside a function call in python? Something like

curr= []
curr.append(num = num/2)

Upvotes: 4

Views: 623

Answers (3)

msw
msw

Reputation: 43497

Nopey. Assignment is a statement. It is not an expression as it is in C derived languages.

Upvotes: 8

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95509

Even if you could, side-effecting expressions are a great way to make your code unreadable, but no... Python interprets that as a keyword argument. The closest you could come to that is:

class Assigner(object):
   def __init__(self, value):
      self.value = value
   def assign(self, newvalue):
      self.value = newvalue
      return self.value

 # ...
 num = Assigner(2)
 curr = []
 curr.append(num.assign(num.value / 2))

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881553

I'm pretty certain I remember one of the reasons Python was created was to avoid these abominations, instead preferring readability over supposed cleverness :-)

What, pray tell, is wrong with the following?

curr= []
num = num/2
curr.append(num)

Upvotes: 4

Related Questions