What are the parentheses for at the end of Python method names?

David Kennell picture David Kennell · Aug 20, 2015 · Viewed 8.4k times · Source

I'm a beginner to Python and programming in general. Right now, I'm having trouble understanding the function of empty parentheses at the end of method names, built-in or user-created. For example, if I write:

print "This string will now be uppercase".upper()

...why is there an empty pair of parentheses after "upper?" Does it do anything? Is there a situation in which one would put something in there? Thanks!

Answer

Martijn Pieters picture Martijn Pieters · Aug 20, 2015

Because without those you are only referencing the method object. With them you tell Python you wanted to call the method.

In Python, functions and methods are first-order objects. You can store the method for later use without calling it, for example:

>>> "This string will now be uppercase".upper
<built-in method upper of str object at 0x1046c4270>
>>> get_uppercase = "This string will now be uppercase".upper
>>> get_uppercase()
'THIS STRING WILL NOW BE UPPERCASE'

Here get_uppercase stores a reference to the bound str.upper method of your string. Only when we then add () after the reference is the method actually called.

That the method takes no arguments here makes no difference. You still need to tell Python to do the actual call.

The (...) part then, is called a Call expression, listed explicitly as a separate type of expression in the Python documentation:

A call calls a callable object (e.g., a function) with a possibly empty series of arguments.