variable hell
Mike Meyer
mwm at mired.org
Fri Aug 26 20:24:56 EDT 2005
[The context is totally hosed by top posting and failure to mark
quoted text. I gave up on recovering it.]
"Adriaan Renting" <renting at astron.nl> writes:
> Not in my Python.
>
>>>> for count in range(0, 10):
> ... value = count
> ... exec("'a%s=%s' % (count, value)")
You left in the extra set of quotes. Try this:
>>> for count in range(10):
... value = count
... exec 'a%s = %s' % (count, value)
...
>>> dir()
['__builtins__', '__doc__', '__file__', '__name__', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'count', 'help', 'readline', 'rlcompleter', 'sys', 'value']
I also removed the extraneous parens that you and Rafi both used -
exec is a statement, not a function.
Of course, your two examples are better done using imp and globals() or
locals().
<mike
>>>> dir()
> ['__builtins__', '__doc__', '__name__', 'count', 'value']
>>>> for count in range(0, 10):
> ... value = count
> ... exec(eval("'a%s=%s' % (count, value)"))
> ...
>>>> dir()
> ['__builtins__', '__doc__', '__name__', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'count', 'value']
>>>>
>
> I myself use code like this to load user defined classes.
> exec(eval("'from %s import %s' % (script, script)"))
> exec(eval("'self.user_class = %s()' % script"))
> self.user_class.run()
>
> But this can probably be done with the imp module too.
>
>>>>rafi <rafi at free.fr> 08/25/05 6:03 pm >>>
> Adriaan Renting wrote:
>>You might be able to do something along the lines of
>>
>>for count in range(0,maxcount):
>> value = values[count]
>> exec(eval("'a%s=%s' % (count, value)"))
>
> why using the eval?
>
> exec ('a%s=%s' % (count, value))
>
> should be fine
>
> --
> rafi
>
> "Imagination is more important than knowledge."
> (Albert Einstein)
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
Mike Meyer <mwm at mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
More information about the Python-list
mailing list