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

Susan Sarandon
Release: 2024-11-02 03:28:02
Original
401 people have browsed it

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

Restoring an Overwritten Builtin Function

When experimenting in an interactive Python session, it's easy to accidentally overwrite a built-in function like set by assigning it to a variable name. This can be a nuisance, especially if you have a lot of work in progress and don't want to restart your session.

Fortunately, there's a simple way to restore the original set function:

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

This will remove the masking variable name and grant you access to the original function:

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

If you still need to access the original set function, you can always do so through the builtins module:

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

This is useful if you want to override a built-in function but want to retain the ability to call the original function from your override:

<code class="python"># In the Python interpreter
>>> set = lambda x: x
>>> set([1, 2, 2, 3, 4])
[1, 2, 3, 4]
>>> builtins.set([1, 2, 2, 3, 4])
{1, 2, 3, 4}</code>
Copy after login

Remember to check all namespaces for the masking name to avoid confusion. For an overview of scoping rules, see the documentation on Short description of the scoping rules.

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