Derivative of string as a name of list or dictionary (or class?)

Alex Martelli aleax at aleax.it
Fri Jul 26 12:43:34 EDT 2002


John Hunter wrote:
        ...
> If you want to set variable names in the global namespace, I am
> reasonably sure you can do a similar thing by manipulating a global
> object, but I don't know what it is.  You can always use exec, but you
> will probably have people frown at you

Sure, but the frown is first of all against the very task that the
OP wants to perform: setting arbitrary names in the global space.

What if one of the name is 'print'?  Boom.  Python has a couple of
dozen keywords -- what ensures against attempts to redefine one?

Python has dozens of useful builtins -- what if one of the arbitrary
names to be injected happens to overlap with one of the builtins
the program is using?  Potentially even worse and subtler bugs, as
the exec statement will succeed, but any later arbitrary point of
the program may fail mysteriously.

It's a fool's errand, and the only sensible answer to "how do I set
arbitrary global names?" is "don't: you'll regret it".  Setting
arbitrary *attributes* on any object of your choice is a far superior
approach by any measure (you still do have to take care that the
names don't clash with Python keywords, IF you expect to have
Python code using them as attribute names, but that, too, can
most often be avoided).

Using the exec statement has even more downsides, such as
likely horribly slowing down the function that uses it and
making your program totally vulnerable to malicious users.
But I guess any program that WANTS to trample all over any
arbitrary names of its global namespace is self-destructive
enough that such issues may be seen as pluses...


Alex






More information about the Python-list mailing list