Home > Article > Backend Development > How can I restore overridden built-in functions in Python?
Overriding Builtins: Restoring Lost Functionality
Python offers flexibility in defining custom names that can override builtin functions and keywords. However, accidental overwriting can pose challenges in accessing the original functionalities. This article explores a method to restore the original builtin, circumventing the need to restart the session.
When overwriting a builtin, it assumes the value assigned to it. For instance, assigning a variable named 'set' to any value masks the original 'set' function. To restore access, the masking name must be removed.
To do this, execute the 'del' statement followed by the assigned name, as seen in the following example:
>>> set = 'oops' >>> set 'oops' >>> del set >>> set <type 'set'>
This action removes 'set' from the current scope, revealing the original 'set' function. Alternatively, the original builtin can be accessed through the 'builtins' module ('__builtin__' in Python 2), allowing overrides while still retaining access to the original implementation:
>>> import builtins >>> builtins.set <type 'set'>
Keep in mind that the masking name may be defined in different namespaces, including the current one and scopes above it. If locating it proves challenging, refer to the "Short description of the scoping rules?" resource for insights into applicable scopes.
The above is the detailed content of How can I restore overridden built-in functions in Python?. For more information, please follow other related articles on the PHP Chinese website!