0

Suppose I have a Python function that generates a parameterized function like this:

def fgen(a):
    def f(x):
        return a * x
    f.__doc__ = """Multiply x by {}""".format(a)
    f.__name__ = 'F{}'.format(a)
    return f

If I now use it like this:

f2 = fgen(2)
print(f2(2))
help(f2)
print(f2)

I get this output:

4
Help on function F2 in module __main__:

F2(x)
    Multiply x by 2

<function fgen.<locals>.f at 0x1104a5840>

I wondered if it is possible for the last line to be something like:

y = 2 * x

I thought maybe you could do something like:

f.__str__ = lambda object: 'y = {} * x'.format(a)

but this does not seem to have any effect on what is printed. Neither does f.repr.

I know I can create a class with str and call methods to achieve this, but I wanted to do it with just functions if possible.

John Kitchin
  • 2,236
  • 1
  • 17
  • 25
  • Important answer in the duplicate: “No, because `repr(f)` is done as `type(f).__repr__(f)` instead.” – Ry- Sep 08 '17 at 02:46
  • Handy examples of using `class` are provided in this answer: https://stackoverflow.com/questions/22797580/how-to-replace-str-for-a-function – Timofey Chernousov Sep 08 '17 at 03:12

0 Answers0