OO in Python? ^^

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sun Dec 11 08:39:05 EST 2005


On Sun, 11 Dec 2005 10:02:31 +0100, Matthias Kaeppler wrote:

> Brian Beck wrote:
>> def foo(self):
>>     raise NotImplementedError("Subclasses must implement foo")
> 
> That's actually a good idea, though not as nice as a check at 
> "compile-time" (jesus, I'm probably talking in C++ speech again, is 
> there such a thing as compile-time in Python at all?!)

Yes. Python, like Java, compiles your code into byte code which is then
executed by the Python runtime engine.

Back in the early days of computing the distinction between compiled
languages and interpreted languages might have been meaningful, but not so
much today. There is significant fuzzy overlap between the two.



> Another thing which is really bugging me about this whole dynamically 
> typing thing is that it seems very error prone to me:
> 
> foo = "some string!"
> 
> # ...
> 
> if (something_fubar):
>     fo = "another string"
> 
> Oops, the last 'o' slipped, now we have a different object and the 
> interpreter will happily continue executing the flawed program.

Yes, this is one specific error which the Python compiler won't pick up
for you. However, it will pick up the related error:

foo = "some string!"
# ...
if (something_fubar):
    bar = fo # should be foo

assuming there isn't some other name fo which already exists.



> I really see issues with this, can anyone comment on this who has been
> working with Python more than just a day (like me)?

Python works well with test-driven development. Test-driven development
will pick up this sort of error, and many other errors too, with less
effort and more certainty than compile-time checking. The problem with
static typed languages is that they make the programmer do a lot of the
work, just so the compiler can pick up a few extra errors at compile time
rather than at run time.

But since the compiler can't save you from run time errors, you still
should be doing test-driven development. But if you are doing test-driven
development, the value of the static type checking is rather low.

After all, "does it compile?" is only one test out of many, and really the
least important. Lots of code compiles that doesn't work; however no code
that works can possibly fail to compile.

Having said that, static type checking is not utterly useless, and rumour
has it that Python may some day include some version of it.

Oh, if you are tempted to fill your Python code with manual type checks,
using type() or isinstance(), I suggest that you learn about "duck typing"
first. Otherwise known as "latent typing".


-- 
Steven.




More information about the Python-list mailing list