[Tutor] Pseudo-functions and dicts

Andreas Kostyrka andreas at kostyrka.org
Sat Mar 22 09:57:32 CET 2008


Well, there are basically two ways to go at it.

If you want it at module level, you need to generate the functions:

sensor = {'sens1': 200, 'sens2': 300}

for key in sensor.keys():
    def helper(keytofetch=key):
        return sensor[keytofetch]
    globals()[key] = helper
    
print sens1()
print sens2()

Alternatively, if you want to stuff into a class, you can do:

class X:
    def __init__(self):
        self.sensor = {}
    def __getattr__(self, key):
        return lambda : self.sensor[key]

x=X()
x.sensor = {'sens1': 200, 'sens2': 300}

print x.sens1()
print x.sens2()
print x.test() # => raises KeyError

Andreas


Am Freitag, den 21.03.2008, 22:01 -0400 schrieb Shrutarshi Basu:
> I have a dictionary (in a module) which contains values of various
> sensors. I would like a user to be able use to a function syntax to
> get the sensor values, both as a whole and individually. Currently I
> have a function for each value who's sole purpose is to look up the
> corresponding dict value and return. But I don't think this is an
> elegant way to solve the problem. Is there someway I could define a
> single function that responds to all of possible function calls?
> 
> Eg.
> My dict : sensor = {'sens1': 200, 'sens2': 300} etc
> my functions:
> def sens1():
>      return sensor['sens1']
> same for sens2.
> 
> 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)
> I could let the user directly access the dict, but I'm not sure if
> that is a good idea. 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. If there is some sort of non-functional
> dot-separated syntax that I could use, that would be good too.
> Thanks,
> Basu
> 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Dies ist ein digital signierter Nachrichtenteil
Url : http://mail.python.org/pipermail/tutor/attachments/20080322/01225fbe/attachment.pgp 


More information about the Tutor mailing list