Specifing arguments type for a function

Diez B. Roggisch deets at nospam.web.de
Tue Jun 20 06:17:14 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?

Yes and no. You can ensure that the passed object is a list, by calling e.g.

def f(arg):
    if not isinstance(arg, list):
       raise "Not a list!"


Alternatively, you can just use it as an iterable - and the exception will
come from arg not being iterable.

But what you can't do is make python complain about this:

def f(arg):
    for e in arg:
        print e


f(100)

before actually calling f. It will always fail at runtime.

Diez



More information about the Python-list mailing list