implicit variable declaration and access

Scott David Daniels Scott.Daniels at Acm.Org
Tue Jun 14 10:09:39 EDT 2005


Tom Anderson wrote:
> ... If it's not, try:
> x = "myVarName"
> y = "myVarValue"
> locals()[x] = y

Sorry, this works with globals(), but not with locals().
There isn't a simple way to fiddle the locals (the number
is determined when the function is built).

I do, however, agree with you about what to use.  I use:
   class Data(object):
      def __init__(self, **kwargs):
         for name, value in kwargs.iteritems():
             setattr(self, name, value)
      def __repr__(self):
         return '%s(%s)' % (type(self).__name__, ', '.join(
                ['%s=%r' % (name, getattr(self, name))
                 for name in dir(self) if name[0] != '_']))

When I want to fiddle with named values.
     el = Data(a=5, b='3')
     el.c = el.a + float(el.b)
     setattr(el, 'other', getattr(el, 'a') + getattr(el, 'c'))
     el

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list