0

Is it possible to output the content of a user-defined function as a string (not the enumeration, but just the function call):

Function:

def sum(x,y):
    return x+y

Function content as a string:

"sum(), return x+y"

The inspect function might have worked but it seems to be for just python 2.5 and below?

7
  • Why addition() and not addition(self)? Commented Aug 3, 2016 at 15:17
  • 1
    inspect is not for Python 2.5 or below; where did you read that? The inspect module is alive and kicking in the latest Python releases. Commented Aug 3, 2016 at 15:18
  • Edited the question. Commented Aug 3, 2016 at 15:18
  • Right, so why sum() and not sum(x, y)? Commented Aug 3, 2016 at 15:18
  • And what should happen for functions with more than one line of code? Commented Aug 3, 2016 at 15:19

1 Answer 1

2

The inspect module works just fine for retrieving source code, this is not limited to older Python versions.

Provided the source is available (e.g. the function is not defined in C code or the interactive interpreter, or was imported from a module for which only the .pyc bytecode cache is available), then you can use:

import inspect
import re
import textwrap

def function_description(f):
    # remove the `def` statement.
    source = inspect.getsource(f).partition(':')[-1]
    first, _, rest = source.partition('\n')
    if not first.strip():  # only whitespace left, so not a one-liner
        source = rest
    return "{}(), {}".format(
        f.__name__,
        textwrap.dedent(source))

Demo:

>>> print open('demo.py').read()  # show source code
def sum(x, y):
    return x + y

def mean(x, y): return sum(x, y) / 2

def factorial(x):
    product = 1
    for i in xrange(1, x + 1):
        product *= i
    return product

>>> from demo import sum, mean, factorial
>>> print function_description(sum)
sum(), return x + y

>>> print function_description(mean)
mean(), return sum(x, y) / 2

>>> print function_description(factorial)
factorial(), product = 1
for i in xrange(1, x + 1):
    product *= i
return product
Sign up to request clarification or add additional context in comments.

3 Comments

I get the following error: raise IOError('could not get source code') IOError: could not get source code
@BlackHat: then there is no source code to retrieve. Did you define the function in the interactive interpreter? Then there is no source code left to inspect.
I see what you mean. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.