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
Susan SarandonOriginal
2024-12-11 00:09:18759browse

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)

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

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)

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!

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