Newbie can't figure out documentation practices
Fernando Perez
fperez528 at yahoo.com
Fri May 9 15:04:37 EDT 2003
Sean Ross wrote:
> Here's another way:
>
> class dotdict(dict):
> # credit: name 'dotdict' taken from Alex Martelli
> def __getitem__(self, key):
> try:
> instance, attrname = key.split('.')
> except ValueError:
> return dict.__getitem__(self, key)
> return getattr(dict.__getitem__(self, instance), attrname)
>
> class MyClass:
> def __init__(self, z):
> self.z = z
> def test(self, other):
> info = \
> """
> var x = %(x)s
> var y = %(y)s
> var self.z = %(self.z)s
> fun x+y+self.z = %(x)s+%(y)s+%(self.z)s
> var z from other object = %(other.z)s
> z from self plus other = %(self.z)s + %(other.z)s
> """
> x, y = 3, 4
> infodict = dotdict(locals().copy())
> infodict.update(dict([('self', self), ('other', other)]))
> print info % infodict
But this fails the moment you need self.a.b, or self.a.b.c... (unless you
manually update for those as special sub-cases).
I still don't see a generic way of accessing member data without jumping
through hoops. If nothing else, a newbie should be able to expect that if
print "x=%(x)s" % locals()
prints x's value, then
print "self.x=%(self.x)s" % locals()
should similarly work. Principle of least surprise, "Simple is better than
complex" and all that...
Cheers,
f.
ps. As I was going to hit send, I got this from J. Collins by mail:
class evaldict:
def __init__(self, dict):
self.mydict = dict
def __getitem__(self, key):
return eval(key, self.mydict)
This one works generically for arbitrarily nested stuff. This is, I think,
a variation on a trick I've seen before. It's definitely a clean, nice
solution, but considering the 'wartiness' of this issue (IMHO ;), I'd
rather have a canonical solution for it in the language.
But I've beat this horse already in the past with no success, so I'll go
back to my cave :)
More information about the Python-list
mailing list