"casting" Python objects

David LeBlanc whisper at oz.net
Wed May 22 20:32:52 EDT 2002


> -----Original Message-----
> From: python-list-admin at python.org
> [mailto:python-list-admin at python.org]On Behalf Of DJW
> Sent: Wednesday, May 22, 2002 16:29
> To: python-list at python.org
> Subject: "casting" Python objects
>
>
> 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

Unlike a typed language like C++, containers like arry or dictionary are
containers of any object, not just some particular type.

If msg.asNode can discern the type of the Jabber message as it's getting it,
the solution is to create a Message subclass of that type and put it in the
queue. Then insure that each Message subclass has a method called "handler".
Then just call node.get().Handler() et viola!

Dave LeBlanc
Seattle, WA USA






More information about the Python-list mailing list