Is this a good idea or a waste of time?

skip at pobox.com skip at pobox.com
Thu Aug 24 16:12:49 EDT 2006


    Arcadio> Would it be considered good form to begin every method or
    Arcadio> function with a bunch of asserts checking to see if the
    Arcadio> parameters are of the correct type (in addition to seeing if
    Arcadio> they meet other kinds of precondition constraints)? 

If it works for you.  It's not generally considered Pythonic though.  You
should probably read up on "duck typing".  Some food for thought: Do you
normally care that the object passed to foo() is a real honest-to-goodness
file object, or do you just care that it has a write() method?  You will
learn soon enough if it doesn't, and not that much later than if you have an
assert at the beginning of your function.  Of course, sometimes you do truly
care about the type of an object.  Then you test.  When you care.

    Arcadio> This is something I miss from working with more stricter
    Arcadio> languages like C++, where the compiler will tell you if a
    Arcadio> parameter is the wrong type.

It's a mistake to think that Python's typing is somehow less strict than
C++'s.  It's not like Perl where 1 + "2" is valid.  It's simply that its
type checks are performed at run-time, not at compile-time.  If you're
desparate to have some assistance with your code before you run it, check
out pylint and pychecker.

Skip



More information about the Python-list mailing list