1

property is a class in python.

type(property)
<class 'type'>
callable(property)
True

I want to get the source code of the built-in class:

import inspect
inspect.getsource(property)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.9/inspect.py", line 1024, in getsource
    lines, lnum = getsourcelines(object)
  File "/usr/lib/python3.9/inspect.py", line 1006, in getsourcelines
    lines, lnum = findsource(object)
  File "/usr/lib/python3.9/inspect.py", line 817, in findsource
    file = getsourcefile(object)
  File "/usr/lib/python3.9/inspect.py", line 697, in getsourcefile
    filename = getfile(object)
  File "/usr/lib/python3.9/inspect.py", line 666, in getfile
    raise TypeError('{!r} is a built-in class'.format(object))
TypeError: <class 'property'> is a built-in class
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
showkey
  • 482
  • 42
  • 140
  • 295
  • It's implemented in C, so it doesn't have any Python source code to show. – Alexander Jun 12 '23 at 00:56
  • How can get the c source code which implement property class? – showkey Jun 12 '23 at 00:57
  • The c source code which implement property class is kept as secret? – showkey Jun 12 '23 at 00:58
  • 2
    CPython is open source. I don't know of an automatic way to find the C source, but I found it by hand. The declaration is here: https://github.com/python/cpython/blob/58f5227d7cdff803609a0bda6882997b3a5ec4bf/Objects/descrobject.c#L1958-L2000 – Alexander Jun 12 '23 at 00:59
  • See also [Finding the source code of methods implemented in C?](https://stackoverflow.com/questions/52968628/finding-the-source-code-of-methods-implemented-in-c) – Abdul Niyas P M Jun 12 '23 at 03:20

1 Answers1

1

You're getting this error because in CPython (the most popular implementation of Python, and the one that's you're using) property is implemented natively in C, and has no Python source to show.

Since CPython is open-source, you can poke around and find the C source yourself. For property, it's declared here:

https://github.com/python/cpython/blob/58f5227d7cdff803609a0bda6882997b3a5ec4bf/Objects/descrobject.c#L1958-L2000

You can look at the referenced symbols to see the details, e.g. property_methods is the list of this class' methods, defined here:

https://github.com/python/cpython/blob/58f5227d7cdff803609a0bda6882997b3a5ec4bf/Objects/descrobject.c#L1575-L1581

Alexander
  • 59,041
  • 12
  • 98
  • 151