2

I am trying to get source code of python print using inspect but it is throwing error. Can someone please tell me how to get the source code of python2.7 print statement.

inspect.getsourcefile(print)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-85-6158f5314751> in <module>()
----> 1 inspect.getsourcefile(print)

/usr/lib/python3.4/inspect.py in getsourcefile(object)
    569     Return None if no way can be identified to get the source.
    570     """
--> 571     filename = getfile(object)
    572     all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
    573     all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]

/usr/lib/python3.4/inspect.py in getfile(object)
    534         return object.co_filename
    535     raise TypeError('{!r} is not a module, class, method, '
--> 536                     'function, traceback, frame, or code object'.format(object))
    537 
    538 ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type')

TypeError: <built-in function print> is not a module, class, method, function, traceback, frame, or code object

In [86]: inspect.getsourcefile(builtin.print)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-86-2d1fb60aac58> in <module>()
----> 1 inspect.getsourcefile(builtin.print)

NameError: name 'builtin' is not defined
theBuzzyCoder
  • 2,652
  • 2
  • 31
  • 26

2 Answers2

15

The print function is implemented in C language. That's why you can not reach its source code with the inspect module. The code is here: https://github.com/python/cpython/blob/2.7/Python/bltinmodule.c#L1580

Antoine
  • 1,070
  • 7
  • 11
  • 4
    Here's a link to the current source code if anyone's wondering: https://github.com/python/cpython/blob/3.8/Python/bltinmodule.c#L1821 – computergorl Sep 14 '20 at 21:33
1

There is an implementation of print() in C. The project has the closest generic implementation of print() I've even seen.

And the cpy project aims to implement all built-in methods of Python in C most minimally. It should be helpful.

midnqp
  • 29
  • 1
  • 10