Type checking in python?

Donn Cave donn at u.washington.edu
Thu Jul 20 12:55:29 EDT 2000


Quoth Samuel Scarano <srs25 at cornell.edu>:
...
| Anyway, interesting point, but isn't that what multiple inheritance is for?
| A static (or, for that matter, dynamic) typecheck ensuring that the function
| is called with a string would work fine with unicode strings as long as the
| unicode string class is a subclass of the string class.
|
| Of course, you can't inherit from a built-in type, which is one of the
| uglier features of Python, so it wouldn't work in this case. But is that the
| only reason not to do it? That is, when dealing only with user-defined
| classes, is there ever any real reason to try to fool a function by passing
| an object of the wrong class but with the right methods, rather than
| declaring its class as a subclass of the class the function is expecting?

I just learned while reading another post in this thread that my thoughts
about these matters puts me in the group of people who think deeply about
it, so I'm emboldened to put my 2 cents in!

What about the file object and StringIO?  I mean, supposing that you were
motivated to implement a class like StringIO, and that the file object
were also a Python class, would you make StringIO a subclass of file, or
just implement the interface?

I would just implement the interface, just because there's nothing of
value for me (that I can think of, anyway) in the file implementation.
I want something that ``walks like a duck'', but is not a natural duck
of some exotic species but a completely unrelated thing that shares only
its very simple abstractions.  If I carried along a natural duck in
there, it would be kind of an ancestor fetish, not a useful thing.

Maybe both should inherit from some class that represents the basic
notions that they all implement, even though there wouldn't be any
actual implementation at that level of abstraction, just so's we
could look at the class hierarchy and say ``It's a duck!''.  I guess
some languages do this, Python doesn't.  I think that's good.  Because
we don't respect the ancestor fetish, I don't have to go back to the
author of file and say ``Hey, why don't you pull an abstract base class
up out of your class so I can inherit from it?'' and then to the author
of some library function and say ``Hey, we have this new abstract base
class for "file", so expect that instead and I can use your function.''
I just bolt on the duck stuff and we're ready to go in 10 minutes.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list