Specifing arguments type for a function

bruno at modulix onurb at xiludom.gro
Tue Jun 20 13:15:58 CEST 2006

Rony Steelandt wrote:
>> 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
> What about
> def f(arg):
>    if type(arg)=='list':

FWIW, type(<some_type>) returns a type object, not a string. So your
test will always fail. A right way to write this is:
  if type(arg) is type([]):

>        #do something

Usually a very bad idea. It defeats the whole point of duck-typing. In
most cases, you don't care about the concrete class - all you want is an
object that implements an (implied) interface.

NB : I say 'usually' because there are a very few cases where testing
the concrete class can make sens - but there again, better to use
isinstance() than type().

bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"

More information about the Python-list mailing list