How to easily change the contents of str(function) in python

Question:

Printing a python function directly always gives you an ugly and lengthy string.

def myfunc_addition(a,b):
    return a + b

print(myfunc_addition(1, 2)) # 3
print(str(myfunc_addition)) # <function myfunc_addition at 0x00000215FC2BC8C8>

I want to change this but I have no idea how to achieve it. I googled with "string expression of a function python" and "python how to change str(function)" but they didn’t help me much.

All I could come up with was the code below. This is not great since you have to initialize an object.

class Myfunc:
    def __call__(self, a,b) -> int:
        return a + b
    def __str__(self) -> str:
        return '+'

m = Myfunc()
print(m(1,2)) # 3
print(str(m)) # +

How should I easily change the contents of str(function)?

Asked By: dixhom

||

Answers:

If calling it as str(function) isn’t strictly required, you could add a docstring to the function and then print that:

def myfunc_addition(a, b):
  """+"""
  return a+b

print(myfunc_addition.__doc__)
+

This has the benefit that Python already supports docstrings in the function definition.

Answered By: Craig
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.