Specifing arguments type for a function

Magnus Lycka lycka at carmen.se
Tue Jul 4 02:49:11 EDT 2006


Paolo Pantaleo wrote:
> I have a function
> 
> def f(the_arg):
> ...
> 
> and I want to state that the_arg must be only of a certain type
> (actually a list). Is there a way to do that?

You can state that in your documentation.

You're very likely to get a reasonable runtime error
from this when you start using the_arg in your code.

The pythonic way of programming is not with overly
strict assumptions about typing, but rather by:
a) Assuming as little as possible about the data
    you get from a caller or from a called function.
b) Use a comprehensive suite of automated tests to
    make sure that you find programming errors.

 From a hypothetical point of view, tests can only
find bugs, and never prove that programs are correct,
but in practice, automated tests is one of the best
ways to keep bugs out of your code. Compile time
type checks can only find a small fraction of the
bugs programmers make, and the tests that find the
harder bugs will also find all the type mismatches
that are problematic in any way.

There are those who speculate that we will eventually
have methods to formally prove correctness of programs
through some kind of analysis, but static type checks
and other compile time tests are very far from doing
that.

I think you will find that this approach of assuming
as little as possible about parameters and return
values will make your code both more robust and more
flexible than a traditional approach with static
typing as in C++, Java or ADA etc.



More information about the Python-list mailing list