Marty Wallace
Marty Wallace

Reputation: 35734

Python printing function gets unexpected output at interpreter?

I have the following in a file named seta.py:

def print_name():
    print "hello"

I am doing the following from the interpreter:

import seta

and then

seta.print_name

I would expect the output to be "hello" but it is as follows:

<function print_name at 0x7faffa1585f0>

What am i doing wrong?

Upvotes: 3

Views: 156

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250921

To call a function you need to add ():

seta.print_name()

Otherwise it'll print the str/repr version of that function object.

Demo:

def func():
    print "Hello, World!"
>>> func                         #Returns the repr version of function object
<function func at 0xb743cb54>
>>> repr(func)
'<function func at 0xb743cb54>'
>>> print func                   #Equivalent to `print str(func)`
<function func at 0xb743cb54>

>>> func()                       #Eureka!
Hello, World!

Upvotes: 7

2rs2ts
2rs2ts

Reputation: 11026

If you define a function at the interpreter, and then print the name of the function without the parens, you'll get __repr__ (representation) of the function object, because in Python, functions are objects. That's what you got, but here's a demo.

>>> def foo():
...     return 1
... 
>>> print foo
<function foo at 0x1005fa398>

Parentheses call the function. The call evaluates to the returned result of the function. So when you type foo(), that turns into 1. But without the parentheses, you are just talking about the function itself, not the calling of it. You expected the result of calling it.

As others will point out, you meant to type seta.print_name().

Upvotes: 3

Related Questions