polymorphism w/out signatures?

Donn Cave donn at u.washington.edu
Thu May 6 18:04:15 EDT 2004


In article <997a06e0.0405061128.6768676d at posting.google.com>,
 pugnatio2 at yahoo.com wrote:

> What's the standard way to implement polymorphic behavior in a python
> method, given that method arguments can't declare their types as
> they're being passed in, and method definitions don't have signatures?
> 
> For instance, if I wanted to write a method that auto-detected whether
> it was being passed a string or a tuple/list, how would I do so
> without using type() to identify the parameter's type? Using type() is
> deprecated in the documentation I've read.

type() does what you want to do.  It's not so much that
the function is deprecated, rather the idea behind wanting
to use it in the first place.

A string is a kind of sequence, as are lists and tuples.
If you really want to deal with a string as a variation on
that theme, but there are differences that you have to take
into account, then maybe someone can suggest an approach if
you can describe the issue.

On the other hand, if you want to support a string as an single
value instead of a list or tuple of values, then you're not
really talking about polymorphism here anyway.  When a function
decides to support various unrelated types for a particular
parameter, I don't know what you call that, but it isn't
polymorphism in any useful sense.  It has been done, it's
up to you whether you want to do it, but personally I think
it's bad news because it's confusing and difficult to do right.
A misguided convenience.

Polymorphism is about a function supporting a range of objects
that conform to a certain specification (in Python that's an
implicit specification.)  Like a function written with a file
object in mind can also support a cStringIO object, automatically.
Obviously, type() is the wrong direction in this context, because
that "automatically" part is important.

But type() is also difficult to do right, even if you don't care
about polymorphism, because polymorphism is there whether you
want it or not.  What if you have been checking for StringType
instead of list or tuple, and someone passes a Unicode object?
Is that a string?  Is it StringType?  You're not ready for that
if you haven't explicitly accounted for it, and there's lots of
Python code still in use that was written before there was such
a thing as a Unicode object.

   Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list