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

How to Restore Overwritten Builtin Functions in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-02 14:36:30846browse

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>

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>

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!

Statement:
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