Generating getter methods with exec

Duncan Booth duncan at NOSPAMrcp.co.uk
Tue Mar 19 05:42:34 EST 2002


Neal Norwitz <neal at metaslash.com> wrote in
news:3C967A13.C6074484 at metaslash.com: 

>> So to rephrase the problem a bit: I would like to generate simple
>> getters and setters with rather little decision overhead during the
>> actual accesses. 
> 
>:-) Well in that case:
> 
> class GetterTest1:
>     def __init__(self):
>         self._dict = {'key1': 'one',
>                       'key2': 'two',
>                       'key3': 'three'}
> 
>     def _make_getters(self, dict_name, key_list):
>         for key in key_list:
>             code = "def %(key)s(): return %(dict_name)s['%(key)s']\n"
>             % vars() exec code in self.__dict__, self.__dict__
> 
> 

You still don't need to even consider using exec for this:
>>> class GetterTest2:
	def __init__(self):
	       self._dict = {'key1': 'one',
                      'key2': 'two',
                      'key3': 'three'}
	def _make_getter(self, dict, key):
		def getter():
			return dict[key]
		self.__dict__[key] = getter
	def _make_getters(self, dict, keys):
		for key in keys: self._make_getter(dict, key)

		
>>> g = GetterTest2()
>>> g._make_getters(g._dict, ['key1', 'key2'])
>>> g.key1
<function getter at 0x00958590>
>>> g.key1()
'one'
>>> g.key2()
'two'
>>> 

This is for 2.2, with 2.1 you need to enable nested scopes.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list