Search code examples
pythonpython-3.xpandasbuilt-in

Can a python builtin function be called using an object


Am a newbie to Python. I have come across this code:

Xtrain is a pandas dataframe object with a shape of X train shape= (42000, 784)

But am able to call the python any() builtin function on the object returned by isnull function of a pandas dataframe

train = pd.read_csv(datapath+"/" +"train.csv")
X_train = train.drop(labels=["label"],axis=1)
X_train.isnull().any().describe()

I understood that builtin functions can be called directly from anywhere. Does the above mean that they are accessible to all objects also ? i.e. in some way every class inherits builtin functions ?


Solution

  • The comments already address the question, but for the sake of posting a solution...

    builtin functions can be called from anywhere, on anything - though whether or not they will work depends on whether or not you are passing in a valid input for that function.

    any is a builtin function.

    HOWEVER.. in this case, you are actually working with an any method that belongs to the pd.DataFrame class.

    try dir(pd.DataFrame) .. you will see any listed in there.

    this means it's a function that belongs to the class (making it a method).

    this is NOT the same as the builtin any.

    Further proof...

    import inspect
    
    print(inspect.getfile(any))
    

    output

    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "C:\Users\deden\AppData\Local\Continuum\anaconda3\lib\inspect.py", line 666, in getfile
        type(object).__name__))
    TypeError: module, class, method, function, traceback, frame, or code object was expected, got builtin_function_or_method
    
    print(inspect.getfile(pd.DataFrame.any))
    

    output

    C:\Users\deden\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py