1

I'm using format to test a function in Python. I would like the output of a function

def test(f,k):
    print "{0}({1})={2}".format(f,k,f(k))

given

test(Sqrt,4)

to be

Sqrt(4)=2

But format is giving back the type 'function' and a memory address inside angle braces. Is there a neat way to shorten the output to get what I'm after?

Anil_M
  • 10,893
  • 6
  • 47
  • 74

2 Answers2

4

You are looking to use __name__:

def test(f,k):
    print("{0}({1})={2}".format(f.__name__,k,f(k)))

test(sqrt, 2)

Output:

sqrt(2)=1.4142135623730951

From the "Callable types" section of the Data Model docs here , __name__ is simply:

__name__ func_name : The function’s name.

Read the documentation carefully to understand what is available to you when wanting to use these types of attributes. Typically, this will be available to callable types (e.g. when defining a method or class, the __name__ attribute will be available to you). But if you simply define a non-callable, something like:

x = 5

and try to call x.__name__, you will be met with an AttributeError

idjaw
  • 25,487
  • 7
  • 64
  • 83
2

Unlike most objects in Python, functions have a __name__ attribute set to the name they were defined with. You could use that:

print "{0}({1})={2}".format(f.__name__, k, f(k))

Classes also have a __name__, but most other callables don't. If f is some other kind of callable, you'll have to deal with it differently, in a manner that will depend on what kind of callable it is and whether you control its implementation.

user2357112
  • 260,549
  • 28
  • 431
  • 505