views:

81

answers:

4

I'm learning python. I like to use help() or interinspect.getargspec to get information of functions in shell. But is there anyway I can get the argument/return type of function.

+1  A: 

There is a function called type().
Here are the docs

You can't tell in advance what type a function will return

>>> import random
>>> def f():
...  c=random.choice("IFSN")
...  if c=="I":
...   return 1
...  elif c=="F":
...   return 1.0
...  elif c=="S":
...   return '1'
...  return None
... 
>>> type(f())
<type 'float'>
>>> type(f())
<type 'NoneType'>
>>> type(f())
<type 'float'>
>>> type(f())
<type 'int'>
>>> type(f())
<type 'str'>
>>> type(f())
<type 'float'>
>>> type(f())
<type 'float'>
>>> type(f())
<type 'NoneType'>
>>> type(f())
<type 'str'>

It is usually good practise to only return one type of object from a function, but Python does not force that upon you

gnibbler
+4  A: 

If you mean during a certain call of the function, the function itself can get the types of its arguments by calling type on each of them (and will certainly know the type it returns).

If you mean from outside the function, no: the function can be called with arguments of any types -- some such calls will produce errors, but there's no way to know a priori which ones they will be.

Parameters can be optionally decorated in Python 3, and one possible use of such decoration is to express something about the parameters' types (and/or other constraints on them), but the language and standard library offer no guidance on how such decoration might be used. You might as well adopt a standard whereby such constraints are expressed in a structured way in the function's docstring, which would have the advantage of being applicable to any version of Python.

Alex Martelli
A: 

Easy way is to use bpython

Python Learning gets easy & fun again!

alt text

abhiomkar
A: 

Thank you for your answer. Acutually when I asked the question I almost knew the answer. One thing I love python is I can get lots of information thourgh shell without read manual. But I have to accept the reality to check manual sometimes. I hate the feeling that have to look up dictionary when talking with somebody.

leon