[Tutor] Pseudo-functions and dicts
Kent Johnson
kent37 at tds.net
Sat Mar 22 13:38:02 CET 2008
Shrutarshi Basu wrote:
> There are two solutions I've thought about:
> Have a function that takes in the sensor's name as a string and
> responds accordingly. (which might be what I'll end up using)
That is almost the same as using ordinary dict access, with slightly
different syntax, e.g. sensor('sens1') vs sensor['sens1'].
There is actually a function to do this, it is called
sensor.__getitem__. You can give it a new name if you like:
In [1]: sensor = {'sens1': 200, 'sens2': 300}
In [2]: get_value = sensor.__getitem__ # Note no parentheses here
In [3]: get_value('sens1')
Out[3]: 200
> I could let the user directly access the dict, but I'm not sure if
> that is a good idea.
Why not?
> My project requires that the user of my module
> should not have to know about Python's data structures to use the
> values my module returns.
This seems a strange requirement!
> If there is some sort of non-functional
> dot-separated syntax that I could use, that would be good too.
You could make a class whose attributes are the dict keys, then use
attribute access syntax. The Bunch class is handy for this:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308
In [5]: values = Bunch(**sensor) # use sensor as keyword arguments
In [6]: values.sens1
Out[6]: 200
Kent
More information about the Tutor
mailing list