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 functionpalindrome
.first.py
assigns the function referencepalindrome to
the builtins module.first.py
importsis_palindrome
from thesecond.py
file.first.py
callsis_palindrome
function.is_palindrome
function internally callspalindrome
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