AtrributeDict

  • Thread starter Дамјан ГеоргиевÑки
  • Start date
Ð

Дамјан ГеоргиевÑки

I've needed an attribute accessible dict, so I created this.
Are there any obviously stupid shortcomings?

class AttrDict(dict):
def __getattr__(self, name):
try:
return self[name]
except KeyError, e:
raise AttributeError(e)


--
дамјан ( http://softver.org.mk/damjan/ )

Our national drug is alcohol,
we tend to regard the use any other drug with special horror.
-- William S. Burroughs
 
Ð

Дамјан ГеоргиевÑки

I've needed an attribute accessible dict, so I created this.
If you know the attribute names ahead of time, you might consider
using a namedtuple instead.
See
http://docs.python.org/library/collections.html#collections.namedtuple

I do use it, even when I don't know the attribute names, see how:

from collections import namedtuple
def build_namespace_tuple(nsmap):
"""nsmap is a dictionary of XML namespaces (from lxml)"""
namespaces = namedtuple('namespaces', ' '.join(nsmap.keys()))
return namespaces(*['{%s}' % x for x in nsmap.values()])

If I didn't need the dict values wrapped in {} I could've just used:
return namespaces(*nsmap.values())


and it's all fine, just completely immutable, which is not always
desirable.

--
дамјан ( http://softver.org.mk/damjan/ )

Real men don't use backups, they post their stuff on a public ftp server
and let the rest of the world make copies.
-- Linus Torvalds
 
A

alex23

I've needed an attribute accessible dict, so I created this.
Are there any obviously stupid shortcomings?

class AttrDict(dict):
   def __getattr__(self, name):
       try:
           return self[name]
       except KeyError, e:
           raise AttributeError(e)

Have you seen Alex Martelli's Bunch class?

class Bunch:
def __init__(self, **kwds):
self.__dict__.update(kwds)

From http://code.activestate.com/recipes/52308/

With Alex' version, you're not overloading a commonly called method,
nor do you have to worry about the performance of the exception
handling for misses. Plus it's half as long ;)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top