-3

I need to do some introspection in Numpy/Scipy. While it is relatively easy to find info on how to get the help docstring and the arguments, I was not able to get anything concerning how to get info on the returned values. More specifically, I just would like to find which functions return multiple values, or equivalently (more or less) tuples. Any way to do it?

  • 1
    As far as I know, there is no way from Python. Could you just check the documentation? – birdoftheday Jan 07 '16 at 14:28
  • Not sure what you need... May http://stackoverflow.com/questions/9752958/how-can-i-return-two-values-from-a-function-in-python help? – BAE Jan 07 '16 at 14:34
  • also http://stackoverflow.com/questions/919680/can-a-variable-number-of-arguments-be-passed-to-a-function – BAE Jan 07 '16 at 14:36
  • In dynamic languages like Python you cannot infer type of the return value without running the code. The only thing you can try and pray is `help(function_name)`. Otherwise you have to run the fucntion and see what it returns – vrs Jan 07 '16 at 14:39

2 Answers2

0

There is no way you can find this out from Python in general. The answer is not a constant.

def complicated(i):
    if i == 1:
        return 0
    elif i == 2:
        return (0,1)
    elif i == 3:
        return [0,1,2]
    elif program_halts(i):
        return {}
    else
        return "Nope"

What is worse, even if you know the inputs, you can't tell the result without solving the halting problem.

Your only chance is to read the documentation.

0

The documentation ought to tell you, but you can test at runtime if you really need to:

 r = something()

 if type(r)==tuple or type(r)==list:
    for rn in r:
       # do something with each returned value
       # (which might include further checking if it's a list or a tuple)

 elif type(r)==int or type(r)==float:
    # it's a scalar numeric value

 else:
     raise ValueError( "Can't handle {}".format(r) )

In passing a function that returns a list or a tuple should return a list or a tuple of length 0 or 1 to indicate that there was nothing or only one value to return. I have seen codes where you get None, a scalar, or a tuple/list, which makes using the result unnecessarily complex!

nigel222
  • 7,582
  • 1
  • 14
  • 22