“Real work” with Python

I just stumbled across Benjamin Carlyle’s piece titled Hungarian Notation Revisited. He’s replying to a reply to a blah blah of an article by Joel on (among other things) differentiating “safe” and “unsafe” strings in web apps.

I absolutely agree with his point that Hungarian notation is broken because it asks the programmer to do the compiler’s job. I also think it makes code much harder to read, because you’re constantly tripping over details that are (usually) irrelevant to the underlying algorithm.

He goes on to suggest that Python isn’t suitable for “real work” because of its “lack of ability to state the expectations of a particular function”. His premise is wrong, and I also believe his conclusion is wrong, but I leave that as matter of religion opinion.

Strict typing in Python is not the default, but it is painless:

class SafeString(str):
    def __init__(self, value):
        # check value is 'safe' here, then call super class constructor
        str.__init__(self, value)

def only_print_safe_string(s):
    assert isinstance(s, SafeString)
    print s

s = SafeString('This is a safe string')

only_print_safe_string(s)
only_print_safe_string('This will not get printed')

Coming from C or C++ that probably seems a bit weird. “I have to add an assertion just to get type checking?”

But if you think about it, in a dynamic language, that’s all type checking is, an assertion at the function entry point. Python gives you the flexibility to do it when you need to, but only then.

I would also argue that strict typing on its own, is rarely enough to do proper Design by Contract. In most cases the prerequisites for a function can not be expressed simply by the types of the arguments, you need to assert something about their values. And in those cases, even in C and C++, what you end up with is assert.

Posted by mike on Monday May 16th, 2005, tagged with

Comments are closed.