How safe is modifying locals()?
Stefan Schwarzer
sschwarzer at sschwarzer.net
Sat Jul 26 08:49:41 EDT 2003
Hi Paul
Paul Paterson wrote:
> This is a very interesting (and Pythonic) approach, thanks for
> suggesting it! This is certainly what I would try to do if I were
> writing the code from scratch. It may be possible to construct a
> "namespace" type object which gets passed to the function.
I think the most common way to make a namespace in Python is
class my_namespace: pass
...
my_namespace.a = 'foo'
my_namespace.b = 'bar'
Such namespaces are very similar to dictionaries:
my_namespace = {}
...
my_namespace['a'] = 'foo'
my_namespace['b'] = 'bar'
but the first approach is a bit more readable.
If you need many containers, you could use:
class Container:
pass
c1 = Container()
c2 = Container()
...
c1.foo = 'foo'
c2.foo = 'bar'
Of course, if you have a better name for your container, that's even
better. Think of Ian's Point example. :-)
Stefan
More information about the Python-list
mailing list