variable hell
Robert Kern
rkern at ucsd.edu
Thu Aug 25 12:22:15 EDT 2005
Ron Garret wrote:
> If you really want to make something like this work you can define a
> class that would work like this:
>
> vars = funkyclass()
> varname = 'x'
> vars[varname] = value
> vars.x
>
> But this is clearly a design mistake. Either you know the names of the
> variables when you write the code or you do not. If you know them you
> can simply assign them directly. If you do not know them then you can't
> put them in the code to read their values anyway, and what you need is
> just a regular dictionary.
In fact, I do this all of the time.
class Bunch(dict):
def __init__(self, *args, **kwds):
dict.__init__(self, *args, **kwds)
self.__dict__ = self
It's a lifesaver when you're working at the interactive prompt. In the
bowels of my modules, I may not know what the contents are at code-time,
but at the prompt I probably do. Bunch assists both usages.
--
Robert Kern
rkern at ucsd.edu
"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
More information about the Python-list
mailing list