Home > Backend Development > Python Tutorial > Why Does `str = str(...)` Cause a TypeError in Python?

Why Does `str = str(...)` Cause a TypeError in Python?

Patricia Arquette
Release: 2024-12-09 07:14:06
Original
798 people have browsed it

Why Does `str = str(...)` Cause a TypeError in Python?

Redefining Built-ins: Understanding the TypeError in 'str = str(...)'

In Python, modifying built-in objects can lead to unexpected errors. Consider the following code:

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

example(1)
example(2)
Copy after login

Upon executing this code, you may encounter two different scenarios. The first call to example() succeeds, while the second call raises a TypeError. This is because the second assignment to str redefines its meaning.

The Role of str()

In Python, str() is the predefined function that converts an object to a string. Assigning str to a new value overwrites this built-in functionality. By declaring str as global, you're indicating that it should refer to a top-level variable outside the function.

Correcting the Code

To resolve the TypeError, you have two options:

  1. Use a Custom Variable: Choose a different name for the local variable within the example() function. Avoid using reserved Python names like str.
  2. Remove the global Statement: Delete the global statement before assigning a new value to str. This will prevent modifying the global str reference within your function.

Remember, modifying built-in objects can have unintended consequences. Stick to using local variables within functions to prevent conflicts with Python's default behavior.

The above is the detailed content of Why Does `str = str(...)` 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