1

I want to be able to repr() on a class in python which has functions stored in the class's variables so I can reproduce the same functions later when I eval() said output.

Here's an example to illustrate my problem:

class Example:
    def __init__(self, func):
        self.func = func

    def __repr__(self):
        return repr(self.func)


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


example = Example(add)
print(repr(example))

When I run that code, the output I get is:

<function add at 0x7f6ea0e96e18>

Is there any way of making a repr() which would output something that can then be eval()ed to a callable function. Ideally, I'd like an output like:

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

martineau
  • 119,623
  • 25
  • 170
  • 301
Bee Taylor
  • 31
  • 3
  • 1
    If it's a named function, you could just use the function name. If it's a lambda, you could use the lambda expression. But in either case, you won't get any parent context (if there is any), so there are limits to what you can do. – Tom Karzes Oct 18 '20 at 13:07
  • You might be able to use something like this, https://stackoverflow.com/questions/427453/how-can-i-get-the-source-code-of-a-python-function , but this whole thing sounds like a really weird thing to do – Ron Serruya Oct 18 '20 at 13:13

1 Answers1

2

You can do it with Python's inspect module:

import inspect


class Example:
    def __init__(self, func):
        self.func = func

    def __repr__(self):
        return inspect.getsource(self.func)


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


example = Example(add)
print(repr(example))

Output:

def add(x, y):
    return x + y
martineau
  • 119,623
  • 25
  • 170
  • 301