See exactly what a function has returned

Peter Grayson jpgrayson at gmail.com
Wed Sep 15 14:29:59 EDT 2004


> > def print_whats_returned(function):
> >      ## A function that shows what another function has returned
> >      ## as well as the 'type' of the returned data.
> >      print function
> >      print type(function)

This function does not do what you are expecting; type(function) does
not return the type that function returns, it returns the type of the
object passed in.

def foo():
  return 42

>>> print foo
<function foo at 0xf6f888ec>
>>> print type(foo)
<type 'function'>

Because Python is a dynamically typed language, it is not possible for
the interpreter to know what type of object a function returns without
executing it. In fact, it is possible for a function to return
different kinds of things. For example:

def bar(x):
  if x == 0:
    return 42
  elif x== 1:
    return "Forty-two"
  else:
    return None

In a statically typed language, like C, we neccessarily know what type
of thing is returned and we know it at compile-time. In Python, the
type of the returned object is only bound at run-time. In practice,
this means that we usually have to "just know" what a function returns
by knowing the intended semantics of the function. That said, you
could write a function like this that tells you about the return type
of a function for a given invocation of that function ...

def characterize(f, *args):
  r = f(*args)
  print type(r)

>>> characterize(bar, 0)
<type 'int'>
>>> characterize(bar, 1)
<type 'str'>
>>> characterize(bar, 2)
<type 'NoneType'>

Hope this helps.

Pete



More information about the Python-list mailing list