-2

The function definitions for built-in functions such as print, input, etc., cannot be seen because they have been written in C. Is that the case for all built-in functions, or is there any built-in function that has been written in Python?

Edit: I am specifically talking about the CPython implementation.

khelwood
  • 55,782
  • 14
  • 81
  • 108
multigoodverse
  • 7,638
  • 19
  • 64
  • 106
  • That would depend on the specific Python implementation, just as in https://stackoverflow.com/questions/9451929/base-language-of-python – Eugene Sh. May 12 '22 at 14:15
  • 1
    Define "builtin". Python comes with a vast default library, some of which is written in Python. – deceze May 12 '22 at 14:18
  • Specifically for CPython - it is open-source, and you can examine it to answer your question – Eugene Sh. May 12 '22 at 14:21
  • @deceze I mean the ones that are listed with `dir(builtins)` – multigoodverse May 12 '22 at 14:24
  • I would think that they're probably all in C. But you could of course go through them one by one and see if you find one that isn't. Not sure what that exercise would be good for though… – deceze May 12 '22 at 14:39
  • A Stack Overflow question should be about _a specific problem you actually face_. What practical problem could an answer to this question _possibly_ help you solve? – Charles Duffy May 12 '22 at 15:39

1 Answers1

1

I asked myself the same question a few weeks ago. Here is what I tried :

import inspect

for builtinname in dir(__builtins__):
    try:
        builtin = getattr(__builtins__, builtinname)
        src = inspect.getsource(builtin)
        srcfile = inspect.getsourcefile(builtin)
        print(f"Source for {builtinname} is in {srcfile} :")
        print(src)
    except TypeError as e:
        # inspect.getsource throw a TypeError when called on a builtin
        # it is not a documented behavior
        print(f"Source cannot be found for builtin {builtinname}")

The only builtins attribute with python source availaible is __loader__. When you look about it you understand that it is not really a builtin.

So the final answer to your question is no. There is no builtin written in pure Python in the CPython implementation.

Niko B
  • 751
  • 5
  • 9