Home > Backend Development > Python Tutorial > How to Restore Overwritten Builtin Functions in Python?

How to Restore Overwritten Builtin Functions in Python?

Mary-Kate Olsen
Release: 2024-11-02 14:36:30
Original
961 people have browsed it

How to Restore Overwritten Builtin Functions in Python?

Restoring an Overwritten Builtin

Overwriting a builtin function, such as set, while working within an interactive Python session can be frustrating. This article presents a simple yet effective solution to restore access to the original builtin without the need to restart the session.

Accessing Builtins Through Builtins Module

One way to restore an overwritten builtin is by accessing it through the builtins module. In Python 3, this module is named builtins. In Python 2, it is known as __builtin__, with underscores and the absence of an "s". Using this method, one can override a builtin but still retain access to the original function:

<code class="python">>>> import builtins
>>> builtins.set
<type 'set'></code>
Copy after login

Deleting the Masking Name

A more straightforward solution is simply deleting the name that is masking the builtin. This can be achieved with the del statement:

<code class="python">>>> set = 'oops'
>>> set
'oops'
>>> del set
>>> set
<type 'set'></code>
Copy after login

Exploring Scopes for Masking Name

If trouble locating the masking name arises, it is advisable to check all namespaces from the current namespace up to the built-ins. Understanding scoping rules in Python can assist in identifying the namespace where the masking name is defined.

The above is the detailed content of How to Restore Overwritten Builtin 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