How to add builtin functions?

Viewed 13994

I am new to python programming. How can I add new built-in functions and keywords to python interpreter using C or C++?

4 Answers

for python 3.6 onward use import builtins.


# example 1

import builtins

def f():
    print('f is called')

builtins.g = f

g() # output = f is called

####################################
# example 2

import builtins

k = print

def f(s):
    k('new print called : ' + s)

builtins.print = f

print('abc') # output = new print is called abc


While David Wolever's answer is perfect, it should be noted again that the asker is new to Python. Basically all he wants is a global function, which can be done in two different ways...

  1. Define a function in your module and use it.
  2. Define a function in a different module and import it using the "from module import *" statement.

I think the asker's solution is the 2nd option and anyone new to Python having this question should look in to the same.

For an advance user, I would agree with Wolever's suggestion that it is a bad idea to insert a new function in to the builtin module. However, may be the user is looking for a way to avoid importing an always-used module in every script in the project. And that is a valid use case. Of course the code will not make sense to people who aren't part of the project but that shouldn't be a concern. Anyways, such users should look in to the PYTHONSTARTUP environment variable. I would suggest looking it up in the Index of the Python documentation and look at all links that talks about this environment variable and see which page serves your purpose. However, this solution works for interactive mode only and does not work for sub-main script.

For an all around solution look in to this function that I have implemented: https://drive.google.com/file/d/19lpWd_h9ipiZgycjpZW01E34hbIWEbpa/view

Yet another way is extending or embedding Python and it is a relatively complex topic. It is best to read the Python documentation on the same. For basic users, all I would say is that...

  • Extending means adding new builtin modules to the Python interpreter.
  • Embedding means inserting Python interpreter into your application.

And advanced users already know what they are doing!

You can use builtins module.

Example 1:

import builtins

def write(x):
    print(x)

builtins.write = write

write("hello")

# output:
# Hello

Example 2:

import builtins

def hello(*name):
    print(f"Hello, {' '.join(name)}!")

builtins.hello = hello

hello("Clark", "Kent")

# output:
# Hello, Clark Kent!
Related