argument type
It's me
itsme at yahoo.com
Tue Dec 28 00:41:23 EST 2004
Steve,
The argument I wish to pass is either one string, or a list of strings, or a
tuple of strings.
For instance, I have:
def abc(arg1, arg2, arg3)
Let say that I expect arg1 and arg3 to be a number, and arg2 can be either
one string, or a bunch of strings and I need to do something on each of the
strings passed down. So, using the isinstance function suggested, I can
have:
def abc(arg1, arg2, arg3)
if isinstance(arg2,(list,tuple)):
for item in arg2:
abc(arg1, item)
else:
# do whatever with arg2 and I know now arg2 is a single instance
of a string
...
This way, when I invoke the function, I don't have to always remember the []
like:
abc(1,["String 1",],5)
I can simply do:
abc(1,"String 1",5)
and likewise, I can do:
abc(1,["String 1","String 2"],5)
Am I on the right track?
"Steven Bethard" <steven.bethard at gmail.com> wrote in message
news:hd6Ad.244202$5K2.52003 at attbi_s03...
> 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