namespace dictionaries ok?
Bengt Richter
bokr at oz.net
Tue Oct 25 01:16:40 EDT 2005
On Tue, 25 Oct 2005 03:10:17 GMT, Ron Adam <rrr at ronadam.com> wrote:
>Simon Burton wrote:
>
>> Yes!
>>
>> I do this a lot when i have deeply nested function calls
>> a->b->c->d->e
>> and need to pass args to the deep function without changing the
>> middle functions.
>
>Yes, :-) Which is something like what I'm doing also. Get the
>dictionary, modify it or validate it somehow, then pass it on. I also
>find that when I'm passing variables as keywords,
>
> foo(name=name, address=address, city=city)
>
>I really don't want (or like) to have to access the names with
>dictionary key as *strings* in the function that is called and collects
>them in a single object.
>
>
>> In this situation I think i would prefer this variation:
>>
>> class Context(dict):
>> def __init__(self,**kwds):
>> dict.__init__(self,kwds)
>> def __getattr__(self, name):
>> return self.__getitem__(name)
>> def __setattr__(self, name, value):
>> self.__setitem__(name, value)
>> def __delattr__(self, name):
>> self.__delitem__(name)
> >
>> def foo(ctx):
>> print ctx.color, ctx.size, ctx.shape
>>
>> foo( Context(color='red', size='large', shape='ball') )
>>
>>
>> This is looking like foo should be a method of Context now,
>> but in my situation foo is already a method of another class.
>>
Or maybe just add a __repr__ method, if you want to see a readable
representation (e.g., see below).
>> Simon.
>
>I didn't see what you were referring to at first. But yes, I see the
>similarity.
>
>>> class Context(dict):
... def __init__(self,**kwds):
... dict.__init__(self,kwds)
... def __getattr__(self, name):
... return self.__getitem__(name)
... def __setattr__(self, name, value):
... self.__setitem__(name, value)
... def __delattr__(self, name):
... self.__delitem__(name)
... def __repr__(self):
... return 'Context(%s)' % ', '.join('%s=%r'% t for t in sorted(self.items()))
...
>>> print Context(color='red', size='large', shape='ball')
Context(color='red', shape='ball', size='large')
>>> ctx = Context(color='red', size='large', shape='ball')
>>> print ctx
Context(color='red', shape='ball', size='large')
>>> ctx
Context(color='red', shape='ball', size='large')
>>> ctx.color
'red'
Regards,
Bengt Richter
More information about the Python-list
mailing list