"casting" Python objects

DJW dwelch91 at home.nospam.com
Wed May 22 19:28:30 EDT 2002


I know there is no such thing in Python as C-style casting, but I don't
understand what idiom is supposed to be used instead.

Here's the situation: I'm using jabber.py (in a worker thread) to recieve
and send messages for my application. When messages arrive within jabber.py,
a message is created of type jabber.Message and placed in a Queue by my
connection object.
In the main thread, I have a sub-class of jabber.Message, call it "FooMsg"
(there are actually going to be multiple derived types of jabber.Message).
My main application thread has a loop that pulls messages off the Queue and
calls the appropriate handler inside of the message. However, the type of
the messages are of type jabber.Message, not my FooMsg that contains the
handlers:


class FooMsg( jabber.Message):

    def Handler( self ):
        # call approriate handler for message
        ...

 while 1:
    msg = msg_queue.get()  # returns type jabber.Message
    msg.Handler() # ERROR: Handler() is only in type FooMsg!!!

Obviously, one way around this is to only place FooMsgs in the Queue in the
first place. But that seems to defeat the purpose of using a generic,
reusable module like jabber.py. I want to use an unmodified version of
jabber.py if at all possible. The only other way I can figure to do this is
something like:

 while 1:
    msg = msg_queue.get()  # returns type jabber.Message
    node = msg.asNode() # get the contents of the jabber message
    foo_msg = FooMsg( node ) # create a new FooMsg with the message contents
    foo_msg.Handler() # Now we are calling the correct type!

But this seems pretty ugly and inefficient. Is there something more Pythonic
(ie, better) that I'm not seeing here? (also, I know that this is ugly OOP)

Thanks,

Don





More information about the Python-list mailing list