polymorphism (was Re: Type checking in python?)

Oivvio Polite oivvio at cajal.mbb.ki.se
Wed Jul 26 09:14:01 EDT 2000


Hi all.

I'm building a class with a uniform interface and I'm trying to come to
terms with polymorphism in python.

For instance I want the constructor to take either a filename, a file object
or a database connection object.
In C++ this would be done using three different constructors. (I'm not quite
sure about this, cause I don't know C++ :-)
But how should one do it in python.

My first idea was something like this:

class myclass:
    def __init__:(self, arg):
        if type(arg) == types.StringType:
            #check if that's a filename and do the right initialization.
        elif type(arg) == types.FileType:
            #do the initialization in an other way
        # and so on

Looking at resent posts I found a thread on type checking that contained
this unsettling post:

<paul at prescod.net> wrote:
> Let me also point out that in many cases, this style of programming
> would be frowned upon by serious Python programmers. For instance, if
> you check that something is a string, your code will complain when it is
> handed a Unicode string, even though it would probably work fine. If you
> check that it is an open file, then your code probably will complain
> about stringIO file-like objects, even though it would probably work
> fine. If you check that it is an integer, your code will complain about
> integers, even though ti would probably work fine.

What are your experiences? Does the type(arg) checking really become
unmanageable as Paul's post implies? If so what are the alternative routes?

oivvio





More information about the Python-list mailing list