-1

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.

6
  • That would depend on the specific Python implementation, just as in stackoverflow.com/questions/9451929/base-language-of-python Commented May 12, 2022 at 14:15
  • 1
    Define "builtin". Python comes with a vast default library, some of which is written in Python. Commented May 12, 2022 at 14:18
  • Specifically for CPython - it is open-source, and you can examine it to answer your question Commented May 12, 2022 at 14:21
  • @deceze I mean the ones that are listed with dir(builtins) Commented May 12, 2022 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… Commented May 12, 2022 at 14:39

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.