Home  >  Article  >  Backend Development  >  How to Recover an Overwritten Built-in Function in Python?

How to Recover an Overwritten Built-in Function in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 03:08:30896browse

How to Recover an Overwritten Built-in Function in Python?

Recovering an Overwritten Built-in: Addressing Accidental Overwrites

When manipulating variables in an interactive Python session, it's possible to unintentionally overwrite builtin functions. This can be frustrating, especially if you don't want to restart your session to restore access. Is there a way to undo this overwrite without losing valuable data?

Solution:

To retrieve the original builtin function without restarting the session, you can simply delete the variable that's masking it. For instance:

>>> set = 'oops'
>>> set
'oops'
>>> del set
>>> set
<type 'set'>

This will restore the built-in set function to its original state.

Alternative Access:

If you still need to access the original built-in but want to maintain the overwrite, you can use the builtins module. In Python 2, use __builtin__; in Python 3, use builtins.

>>> import builtins
>>> builtins.set
<type 'set'>

This allows you to defer to the original function while overriding the built-in.

Locating the Masking Name:

If you're unsure which namespace contains the masking variable, check your current namespace and any parent namespaces, including the built-in namespace. Refer to resources like "Short description of the scoping rules?" for more details.

The above is the detailed content of How to Recover an Overwritten Built-in Function 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