lanto03 / couchdb-python

Automatically exported from code.google.com/p/couchdb-python
Other
0 stars 0 forks source link

Allow dotted notation for accessing items in python views #110

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
What steps will reproduce the problem?
1. Similar to javascript (and Genshi), it would be nice to allow dotted 
notation for accessing items in dictionaries when using python map 
functions
2.This makes it simpler to write and debug map functions 
3.Practicality beats purity

What is the expected output? What do you see instead?

Instead of writing doc['type'], I want to be able to write doc.type. Nested 
dictionaries should also be supported: doc['mapping']['key'] -> 
doc.mapping.key

What version of the product are you using? On what operating system?

0.6.1

Please provide any additional information below.

Example of a dictobj or attrdict:

class DictObj(dict):
    def __getattr__(self, name):
        try: 
            value = dict.__getitem__(self, name)
        except KeyError:
            raise AttributeError

        # Check for nested dictionaries
        if value.__class__ is dict:
            value = DictObj(value)

        return value

However this function is a lot slower than using plain dictionaries (15x). The 
reason for it is not the code above, but the fact that __getattr__ is 
slow to find. A better approach is to cache the items as attributes:

class DictObj(dict):
    def __getattr__(self, name):
        try: 
            value = dict.__getitem__(self, name)
        except KeyError:
            raise AttributeError

        # Check for nested dictionaries
        if value.__class__ is dict:
            value = DictObj(value)

        # Cache as attribute since __getattr__ is very slow
        setattr(self, name, value)
        return value

The code above will run just as fast as a plain dictionary, but it should be 
made read only. But then again docs in map functions should 
probably not be modified.

http://code.activestate.com/recipes/361668/

http://stackoverflow.com/questions/224026/javascript-style-dot-notation-for-dict
ionary-keys-unpythonic

Original issue reported on code.google.com by dbrat...@gmail.com on 20 Dec 2009 at 10:16

GoogleCodeExporter commented 8 years ago

Original comment by matt.goo...@gmail.com on 25 Feb 2010 at 4:25

GoogleCodeExporter commented 8 years ago
Personally, I'm -1 on this. It just doesn't seem worth the effort. It's Python, 
it's a dict, that's just how they are.

Original comment by matt.goo...@gmail.com on 9 Feb 2011 at 11:03

GoogleCodeExporter commented 8 years ago
Agreed.

Original comment by djc.ochtman on 10 Feb 2011 at 7:55