Specifing arguments type for a function
Maric Michaud
maric at aristote.info
Tue Jun 20 07:28:01 EDT 2006
Le Mardi 20 Juin 2006 12:29, Rony Steelandt a écrit :
> What about
> def f(arg):
> if type(arg)=='list':
> #do something
And if arg's type is subclass of list ?
The problem with isinstance is : and if arg is not of type list but is a
sequence (a instance of UserList for example) ?
The general case in python is duck typing, that means you define apis that
accept file-like object, iterables, dict-like (mapping) objects, string like
objects...
The problem with iterables is that they don't all implement the __iter__
attribute, for compatibility purpose the right test should be :
if not getattr(arg, '__iter__') and not getattr(arg, '__getitem__') :
raise ValueError('Function accepts only iterables') # or error handling
code
--
_____________
Maric Michaud
_____________
Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
More information about the Python-list
mailing list