argument type

Steven Bethard steven.bethard at gmail.com
Tue Dec 28 00:31:57 EST 2004


It's me wrote:
> A newbie question.
> 
> How can I tell from within a function whether a particular argument is a
> sigular type, or a complex type?
> 
> For instance, in:
> 
>     def abc(arg1)
> 
> How do I know if arg1 is a single type (like a number), or a list?
> 
> In C++, you would do it with function overloading.  If arg1 is always simple
> type, I wouldn't care what it is.  But what if I *do* need to know whether
> arg1 is a list or not?
> 
> I hate to have to have 2 functions: 1 for simple types, and one for list
> types and then do something like:
> 
>     abc_simple(1.0)
>     abc_list([1.0,2.0])
> 

Generally, if I have a function that might take one or more args, I'd 
write it like:

     def abc(*args)

and then call it with one of the following:

     abc(1.0)
     abc(1.0, 2.0)
     abc(*[1.0, 2.0])

If you're really stuck with the one argument signature, I tend towards 
the "ask forgiveness rather than permission" instead of the "look before 
you leap" style.  Something like:

     def abc(arg1):
         try:
             x = iter(arg1)
         except TypeError:
             x = iter([arg1])
         # now do whatever you want with x

Note that this might give you some problems if you want to pass in 
strings (since they're iterable).  Can you give some more specifics on 
the problem?  What is the actual function you want to write and what 
kind of arguments to you expect to receive?

Steve



More information about the Python-list mailing list