3

I want to programmatically get the source code for a given class property (e.g., pandas.DataFrame.iloc). I tried using inspect.findsource(), which works fine for classes and functions. However, it doesn't work for properties.

import pandas
import inspect

type(pandas.DataFrame) # type
inspect.findsource(pandas.DataFrame)  # works ok

type(pandas.DataFrame.apply) # function
inspect.findsource(pandas.DataFrame.apply)  # works ok

type(pandas.DataFrame.iloc) # property
inspect.findsource(pandas.DataFrame.iloc) # throws exception
TypeError: module, class, method, function, traceback, frame, or code object was expected, got property

Why inspect cannot find source for property? How can I programmatically get the source code (or source file path) for a given property?

Ida
  • 2,919
  • 3
  • 32
  • 40
  • If I am correct `property` is implemented in [C](https://github.com/python/cpython/blob/3191391515824fa7f3c573d807f1034c6a28fab3/Objects/clinic/descrobject.c.h#L68). That could be the cause of this exception. `findsource` [does not work with object if it is implemented in C](https://stackoverflow.com/questions/52968628/finding-the-source-code-of-methods-implemented-in-c) – Abdul Niyas P M Jun 19 '19 at 14:21
  • 1
    the magic `??pd.DataFrame.iloc` works pretty well in Jupyter. – Quang Hoang Jun 19 '19 at 14:35
  • If you know it’s a property, you can examine its attributes to find the underlying functions. (There can be up to 3, each from its own file!) – Davis Herring Jun 19 '19 at 15:25
  • @QuangHoang right! But `??pd.DataFrame.iloc` gives a popup in Jupyter. Can I redirect the content in popup to a variable? – Ida Jun 19 '19 at 15:27
  • @Ida now that's beyond my knowledge :-) – Quang Hoang Jun 19 '19 at 15:29

0 Answers0