views:

69

answers:

3

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

curr= []
curr.append(num = num/2)
+4  A: 

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)
paxdiablo
Well, I see your point, but I don't see why `cur.append(num=num/2)` is less readable than something like `[x for x in range(1000,9999) if not [t for t in range(2,x) if not x%t]]`
Falmarri
I don't use those ones either :-) I'm more your "classical" Python user.
paxdiablo
A: 

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))
Michael Aaron Safyan
Why, pray tell, would you even think of the above. ;)
msw
@msw, sometimes one's transcribing a "reference algorithm" from C to Python, for example, and in a first phase of such a transcription staying as close to the structure of the C code as feasible is an excellent idea (one refactors _later_ to make the code decent Python, faster, etc, _after_ one has a working Python implementation of the reference algorithms). Slightly different, but not drastically so, analogous considerations, can apply in using Python to prototype code for later transcription into C: the closer to C's structure the prototype is, the easier the transcription will be.
Alex Martelli
@alex, first of all, note the winky smiley `;)`, then note the lexical parallelism to the second sentence of paxdiablo's answer. Then note that the "because I can, but really, don't" of Mr. Safyan's answer and how it isn't anywhere close to the equivalent C-like expression. cf. http://en.wiktionary.org/wiki/levity
msw
+7  A: 

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

msw