Home > Backend Development > Python Tutorial > Why Does Redefining the `str` Function Cause a TypeError in Python?

Why Does Redefining the `str` Function Cause a TypeError in Python?

Susan Sarandon
Release: 2024-12-11 00:09:18
Original
697 people have browsed it

Why Does Redefining the `str` Function Cause a TypeError in Python?

Overwriting Built-in Functions

Why does the code snippet below result in a TypeError the second time it's executed?

def example(parameter):
    global str
    str = str(parameter)
    print(str)

example(1)
example(2)
Copy after login

When executing the first time, the program runs without issues. However, upon calling it a second time, an error is thrown:

TypeError: 'str' object is not callable
Copy after login

Analysis

This error occurs because the code redefines the built-in str function within the example function. By using the global keyword and assigning a new value to str, the code overwrites the original implementation of the string type.

Resolution

To fix this issue, avoid redefining built-in functions like str. Instead, use a different name for the local variable and remove the global statement:

def example(parameter):
    local_string = str(parameter)
    print(local_string)
Copy after login

The above is the detailed content of Why Does Redefining the `str` Function Cause a TypeError 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