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

Barbara Streisand
Release: 2024-11-02 03:08:30
Original
893 people have browsed it

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

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

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!

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!