How can I restore overridden built-in functions in Python?

Barbara Streisand
Release: 2024-10-30 07:56:03
Original
848 people have browsed it

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'>
Copy after login

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'>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!