-1

When I printed my function (without the function call),

def loss(y_true, y_pred): 
    return backend.sum(backend.abs(y_true - y_pred))

I got something like

<function __main__.loss>

I need it to return a string like

Absolute Error Sum

Most links I looked at explain how to do the same for class objects. How do I define what string the function should return?

Saravanabalagi Ramachandran
  • 8,551
  • 11
  • 53
  • 102

2 Answers2

1

You should be able to edit the __name__ attribute of it:

>>> def f(x): print(x)

>>> f
<function f at 0x7feb2c843a28>

>>> f.__name__ = 'my function'

>>> f
<function my function at 0x7feb2c843a28>

>>> f.__name__
my function

Edit: note that in Python 3, you may have to overwrite the __qualname__ property instead (see https://www.python.org/dev/peps/pep-3155/ and https://github.com/ipython/ipython/issues/5566/).

Viknesh
  • 505
  • 1
  • 4
  • 14
0

You can't customize the default repr of the function type, but you can extract the part you care about and format it however you want.

For example, if you want a friendlier name, the actual name is stored in __name__, so you could print(loss.__name__) if you want to avoid the extra wrapping. This isn't perfect (lambda functions don't have names for instance), but it's better than trying to rewrite the default repr for functions.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271