New function in builtins

Accessing Builtins

Python builtins module contains functions and constants. These functions and constants are available in the interpreter and can be accessed via their name.

>>> max
<built-in function max>
>>> __debug__
True
>>> Ellipsis
Ellipsis
>>>

Buitlins can be accessed via __builtins__ variable.

>>> __builtins__.max
<built-in function max>
>>> __builtins__.Ellipsis
Ellipsis

You can also access bulitins from builtins module.

>>> import builtins
>>> builtins.max
<built-in function max>
>>> builtins.Ellipsis
Ellipsi

Setting functions and variables in builtins

Python import system is executed only once. A variable or reference to a name can be set to buitlins module and can be accessed afterwards. For example, you can add reference to a function palindrome and can be accessed later in the program.

Here is a simple example.

  • first.py defines a function palindrome.
  • first.py assigns the function reference palindrome to the builtins module.
  • first.py imports is_palindrome from the second.py file.
  • first.py calls is_palindrome function.
  • is_palindrome function internally calls palindrome function.
# first.py 
def palindrome(name: str) -> bool:
    return name[::-1] == name


__builtins__.palindrome = palindrome

def greet():
    pass

from second import is_palindrome

print("is malayalam palindrome:", is_palindrome("malayalam"))
print("is tamil palindrome:", is_palindrome("tamil"))

# second.py
def is_palindrome(name: str) -> bool:
    return palindrome(name)

try:
    print(greet())
except NameError:
    print('greet function is not visible')

$ python3 first.py 
greet function is not visible
is malayalam palindrome: True
is tamil palindrome: False

For example, ipython shell sets display function in the IPython shell. Source