Why doesn't pandas daframe.shape have parentheses?

Viewed 514

I am new to ML and pandas.

I was going through a jupyter file of a linear regression program. There I saw

dataframe.head() dataframe.describe() dataframe.shape

Why does the first two have parentheses () and shape doesn't?

I try to run dataframe.shape() and it give error TypeError: 'tuple' object is not callable.

Here's a link to the documentation but it didn't help: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.shape.html

dataframe.shape looks like a function and functions should have (). How to know when a function will not have a ()

2 Answers

Classes can have attributes and methods, attributes are .word, while methods are .word(), or .word(arg1, arg2, etc.)

You won't know in advance whether something you want to call is a method or attribute, but you will if you read the documentation for that class. In that documentation, shape is listed under attributes not under methods, so you can infer from that classification how to use it (i.e. without parentheses). Here's the doc link for pandas dataframes: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html

Make a habit of reading the documentation and it will save you a lot of headache!

This is a Python question and not limited to Pandas. Python uses parentheses as syntactic sugar to "call" the object you initiated the parentheses after.

Suppose you have some object a (this doesn't have to be a function, though functions ARE callable). Then we "call" a by putting parentheses after it.

a()

If a is "callable" it will do something. Otherwise, you'll get an error.

I'll define a stripped down class and show what happens:

class A():
    pass

a = A()
a()

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-353-d08e164f0b26> in <module>
      3 
      4 a = A()
----> 5 a()

TypeError: 'A' object is not callable

However, I can make a callable by defining a method __call__

class A():
    def __call__(self):
        return "Hello World!"

a = A()
a()

'Hello World!'

So to answer your question, df.shape doesn't have a __call__ method. This is common for most attributes of class instances and is definitely true for df.shape.

Related