Passing parameters using **kargs
Holger Türk
htx1 at gmx.de
Tue Jun 8 09:50:28 EDT 2004
Thomas Philips wrote:
> In this case, I'm being driven by intellectual curiosity - though I do
> think the ability to create a string representation of a variable name
OK, try this:
def a (x):
y = "Hello"
print locals ()
a ("World")
> could be useful when printing, and the ability to create a variable
> whose name is specified in a string could be useful when creating
> on-the-fly code.
This sounds like you had prior exposure to PHP or Perl, where
one could do things to print "Hello" like
$a = "b";
$$a = "Hello";
print $b
You can do such things in python, too. In the global namespace
>>> globals () ["u"] = "Hello"
>>> u
'Hello'
>>>
and in class instances using setattr, but *not* with local
variables in functions, because for optimization purposes
the interpreter does not look them up in the locals
dictionary.
In my opinion, these described practices are neither clean
nor particularly useful anyway. And things like this can
happen in your on-the-fly code:
>>> globals () ["i+j"] = "Yuck"
>>>
What now?
Better don't do it.
Greetings,
Holger
More information about the Python-list
mailing list