Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> I'm really sick of writing checks whether my function got values of the correct types, and unittests testing if a class's/function's signature changed in an unexpected way.

Sorry to be blunt, but if every one of your Python functions and methods begins with isinstance() checks for every parameter, you just missed the point of the entire language. Python was built on a foundation of ducktyping, with the mantra that "it's easier to ask forgiveness than permission" (EAFP).

Just use your parameters in whatever way you expect them to be, and either catch the rare Exception there or allow them to bubble up. Here's some suggested reading on the subject:

http://www.canonical.org/~kragen/isinstance/

http://stackoverflow.com/questions/6092992/why-is-it-easier-...



The Python approach means that when an exception is thrown, it's unclear whose fault it is. Is it a bug in the called function, or in the caller for passing a bad parameter? The larger the program the more of a problem this becomes.

It also means that when you change a function signature, the compiler can't tell you all the call sites you need to fix. You have to find them through testing. This is a large barrier to aggressive refactoring.

Even the Python C API provides facilities for checking that arguments have a specific type and raising TypeError if not, so it can't be that completely counter to the intention of the language: http://docs.python.org/c-api/arg.html (see O!)


> It also means that when you change a function signature, the compiler can't tell you all the call sites you need to fix. You have to find them through testing. This is a large barrier to aggressive refactoring.

This is a problem inherit to every dynamic language. You sacrifice brain-dead refactoring for improvements and tradeoffs elsewhere. Not to mention that modern IDEs and tools like Rope [1] can definitely help.

[1] http://rope.sourceforge.net/


Not every function, but often enough that it gets annoying.

It mostly happens when dealing with very tight systems, e.g. a RabbitMQ queue consumer fetching messages from an external system and writing stuff to MySQL & Cassandra.

The general issue is that there are some kinds of data types (integer, string, datetime) that cannot really be duck-typed, i.e. replaced by different objects. In my experience, it is better to catch such type errors sooner rather than later, therefore isinstance() checks.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: