tags:

views:

2064

answers:

9

I've started to use constructs like these:

class DictObj(object):
    def __init__(self):
        self.d = {}
    def __getattr__(self, m):
        return self.d.get(m, None)
    def __setattr__(self, m, v):
        super.__setattr__(self, m, v)

Update: based on this thread, I've revised the DictObj implementation to:

class dotdict(dict):
    def __getattr__(self, attr):
        return self.get(attr, None)
    __setattr__= dict.__setitem__
    __delattr__= dict.__delitem__

class AutoEnum(object):
    def __init__(self):
        self.counter = 0
        self.d = {}
    def __getattr__(self, c):
        if c not in self.d:
            self.d[c] = self.counter
            self.counter += 1        
        return self.d[c]

where DictObj is a dictionary that can be accessed via dot notation:

d = DictObj()
d.something = 'one'

I find it more aesthetically pleasing than d['something']. Note that accessing an undefined key returns None instead of raising an exception, which is also nice.

Update: Smashery makes a good point, which mhawke expands on for an easier solution. I'm wondering if there are any undesirable side effects of using dict instead of defining a new dictionary; if not, I like mhawke's solution a lot.

AutoEnum is an auto-incrementing Enum, used like this:

CMD = AutoEnum()

cmds = {
    "peek":  CMD.PEEK,
    "look":  CMD.PEEK,
    "help":  CMD.HELP,
    "poke":  CMD.POKE,
    "modify": CMD.POKE,
}

Both are working well for me, but I'm feeling unpythonic about them.

Are these in fact bad constructs?

+3  A: 

As far as I know, Python classes use dictionaries to store their attributes anyway (that's hidden from the programmer), so it looks to me that what you've done there is effectively emulate a Python class... using a python class.

Smashery
+1  A: 

I like dot notation a lot better than dictionary fields personally. The reason being that it makes autocompletion work a lot better.

Jason Baker
+7  A: 

With regards to the DictObj, would the following work for you? A blank class will allow you to arbitrarily add to or replace stuff in a container object.

class Container(object):
    pass

>>> myContainer = Container()
>>> myContainer.spam = "in a can"
>>> myContainer.eggs = "in a shell"

If you want to not throw an AttributeError when there is no attribute, what do you think about the following? Personally, I'd prefer to use a dict for clarity, or to use a try/except clause.

class QuietContainer(object):
    def __getattr__(self, attribute):
        try:
            return object.__getattr__(self,attribute)
        except AttributeError:
            return None

>>> cont = QuietContainer()
>>> print cont.me
None

Right?

kevin holzer
I agree creating a class seems like a much cleaner way to handle what he is attempting.
monkut
The key difference is I don't want an exception thrown when the key hasn't been previously defined.
Parand
What part of Kevin's example throws an exception?
Robert Rossney
@Robert: The part where you try "print myContainer.blah" raises AttributeError. In Parand's DictObj, "d.blah" would return None, no exception.
mhawke
What about defining a special __getattr__ method? It could just catch the exception and return none. Lemme fix my code to include that.
kevin holzer
+3  A: 

This is a simpler version of your DictObj class:

class DictObj(object):
    def __getattr__(self, attr):
        return self.__dict__.get(attr)

>>> d = DictObj()
>>> d.something = 'one'
>>> print d.something
one
>>> print d.somethingelse
None
>>>
mhawke
Any possible side effects of using <code>__dict__</code>? If not, I like it.
Parand
If I recall, __dict__ isn't technically part of the python spec. That is, other VMs don't need to implement.I also recall that all current VMs (IronPython, Jython, PyPy) actually *do* use a __dict__ for object dictionaries.
Ryan
+1  A: 

It's not bad if it serves your purpose. "Practicality beats purity".

I saw such approach elserwhere (eg. in Paver), so this can be considered common need (or desire).

zgoda
+6  A: 

Your DictObj example is actually quite common. Object-style dot-notation access can be a win if you are dealing with ‘things that resemble objects’, ie. they have fixed property names containing only characters valid in Python identifiers. Stuff like database rows or form submissions can be usefully stored in this kind of object, making code a little more readable without the excess of ['item access'].

The implementation is a bit limited - you don't get the nice constructor syntax of dict, len(), comparisons, 'in', iteration or nice reprs. You can of course implement those things yourself, but in the new-style-classes world you can get them for free by simply subclassing dict:

class AttrDict(dict):
    __getattr__= dict.__getitem__
    __setattr__= dict.__setitem__
    __delattr__= dict.__delitem__

To get the default-to-None behaviour, simply subclass Python 2.5's collections.defaultdict class instead of dict.

bobince
I tried this with defaultdict, but it's still not returning None for underfined:<pre>>>> d = AttrDict()>>> d.meTraceback (most recent call last): File "<stdin>", line 1, in <module>KeyError: 'me'</pre>
Parand
I settled on a slightly modified version of this, now included in the updated question above.
Parand
defaultdict worked for me - did you remember to include the factory function in the constructor? ie. d= defaultdict(lambda: None). If you forget that bit defaultdict just works like a normal dict. You could also override __init__ in AttrDict to do automatically, perhaps.
bobince
+1  A: 

The one major disadvantage of using something like your DictObj is you either have to limit allowable keys or you can't have methods on your DictObj such as .keys(), .values(), .items(), etc.

Ryan
+1  A: 

It's not "wrong" to do this, and it can be nicer if your dictionaries have a strong possibility of turning into objects at some point, but be wary of the reasons for having bracket access in the first place:

  1. Dot access can't use keywords as keys.
  2. Dot access has to use Python-identifier-valid characters in the keys.
  3. Dictionaries can hold any hashable element -- not just strings.

Also keep in mind you can always make your objects access like dictionaries if you decide to switch to objects later on.

For a case like this I would default to the "readability counts" mantra: presumably other Python programmers will be reading your code and they probably won't be expecting dictionary/object hybrids everywhere. If it's a good design decision for a particular situation, use it, but I wouldn't use it without necessity to do so.

cdleary
A: 

Can anyone get cPickle to work with this minimal Dotdict (in Python 2.5.1, macosx 10.4.11) ?

class Dotdict( dict ):
    def __getattr__(self, attr):
        return self.get(attr, None)

if __name__ == "__main__":
    d = Dotdict( a=1 )
    print d.a, d["a"], d.get( "no", 42 ), d, d.keys(), "%(a)s" % d
    # print "%(no)s" % d  # KeyError

    import cPickle
    ddump = cPickle.dumps( d, -1 )  
        # => TypeError: 'NoneType' object is not callable
    # assert ddump == cPickle.loads( ddump )
Denis