Another reason assignment expressions would be nice (?)
alan at littleford.net
alan at littleford.net
Sat Jul 10 18:41:10 EDT 1999
I need to generate some large text files containing test cases for a
project. I decided to exploit the formatted print '%' and the exec()
function. The whole thing is wrapped up with a class (say foo)
instance which supplies useful functions (such as SomeFunction()) so I
can do things like
a = foo()
a.setTemplate("'A test line %d' % self.SomeFunction()")
...
a.run(100)
Calling run applies exec to the defined templates and so
the idea is the result of this would be hundred lines of:
A test line <somenumber>
(Of course the actual example would be more complicated, and class foo
provides loads of useful generator functions). Now here is the rub, I
might want two lines generated with a related value. Lets assume
SomeFunction() throws a random number, so I can't just call it again,
so what I would like to do is this:
a = foo()
a.setTemplate("'A test line %d' %
(self.i = self.SomeFunction()"))
a.setTemplate("'Same value as above %d' % self.i")
...
a.run(100)
But of course I can't do this because '=' is a statement in the first
template. I could define foo to have some 'assignation' function:
def assign(var, val)
var[0] = val
return val
and then use
"'A test line %d' % self.assign(self.var, self.SomeFunction())"
" 'Same value as above %d' % self.var[0]"
but then the thing gets messy because I have to declare the mutable
array self.var somewhere before using it. All in all it seems I have
to jump through hoops because i = 3 doesn't 'return' the value 3.
Or am I missing something frightfully easy here ..
Tnx
Alan Littleford
alan at littleford.net
More information about the Python-list
mailing list