Move dictionary from instance to class level

Dave Angel davea at ieee.org
Wed Aug 26 11:54:13 EDT 2009


Frank Millman wrote:
> "MRAB" <python at mrabarnett.plus.com> wrote in message 
> news:mailman.444.1251290454.2854.python-list at python.org...
>   
>> An alternative is:
>>
>>     
>>>>> class MyClass(object):
>>>>>           
>> ...     def on_message_received(self, msg):
>> ...         try:
>> ...             getattr(self, "method_%d" % msg)()
>> ...         except AttributeError:
>> ...             raise Exception("Unknown message")
>> ...     def method_0(self):
>> ...         print 'in method_0'
>> ...     def method_1(self):
>> ...         print 'in method_1'
>> ...
>>     
>>>>> my_obj = MyClass()
>>>>> my_obj.on_message_received(0)
>>>>>           
>> in method_0
>>     
>>>>> my_obj.on_message_received(1)
>>>>>           
>> in method_1
>>     
>>>>> my_obj.on_message_received(2)
>>>>>           
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in <module>
>>   File "<stdin>", line 6, in on_message_received
>> Exception: Unknown message
>>     
>
> I like the idea. Unfortunately my real-world situation is a little more 
> complex than my simple example implied.
>
> This is a more typical example -
>
>     (EVT_GETLOGIN
>     ,EVT_LOGOUT
>     ,EVT_GETMENUOPT
>     ,EVT_GOTFOCUS
>     ,EVT_LOSTFOCUS
>     ,EVT_BUTTONCLICKED
>     ,EVT_CHECKBOX
>     ...
>     ) = xrange(28)
>
>     method_dict = {}
>     method_dict[EVT_GETLOGIN] = onGetLogin
>     method_dict[EVT_LOGOUT] = onLogout
>     method_dict[EVT_GETMENUOPT] = onGetMenuOpt
>     method_dict[EVT_GOTFOCUS] = onGotFocus
>     method_dict[EVT_LOSTFOCUS] = onLostFocus
>     method_dict[EVT_BUTTONCLICKED] = onButtonClicked
>     method_dict[EVT_CHECKBOX] = onCheckBox
>
> You can probably figure out from my method names what I am doing here - the 
> messages are sent by a thin client (wxPython), and processed by a server.I 
> am anticipating some "don't do that" responses, but I like the concept, and 
> so far it is very fast and responsive, so I will pursue it for now.
>
> Thanks for the input.
>
> Frank
>
>
>   
Any time I see multiple lists like that which have to stay in synch, I 
think code-smell.

Why not let the EVT's be passed as strings, and avoid the whole mapping 
to integers and mapping back detail?  And name the methods involved in a 
way that you can directly translate the string to the method name?

Barring that, make a single "structure" which lists the event names and 
method names in matched pairs, and derive whatever lists and 
dictionaries you actually need from that one structure.  And that 
structure should be shared between client and server code, perhaps as a 
text file that they both parse.  Or as a stream that's passed from one 
to the other during startup.  That way, consistency between them can be 
regulated (with version string in the file, for example)

DaveA




More information about the Python-list mailing list