Home >Backend Development >Python Tutorial >Why Does Redefining the Built-in `str` Function Lead to a TypeError in String Conversion?
Redefining Built-ins Leads to TypeError in String Conversion
This explains why code assigning to str within a function triggers a TypeError on subsequent calls to that function, unlike initial attempts. The following code snippet demonstrates the issue:
def example(parameter): global str # Declares str as a global variable str = str(parameter) # Redefines str as a string print(str) example(1) # First call: successful string conversion example(2) # Second call: raises a TypeError
Root Cause and Resolution
The global statement in the snippet essentially redefines str, which is a built-in type representing strings. Assigning a new value to str() overrides its default functionality as a function for converting objects to strings.
To resolve this issue, use a different name for the local variable within the function and remove the global statement. For example:
def example(parameter): local_str = str(parameter) # Local variable with a different name print(local_str) example(1) # First call: successful string conversion example(2) # Second call: successful string conversion
Interactive Python Shell Implications
If you encounter this issue in an interactive shell, assigning to the global str() persists unless explicitly addressed. One method to resolve this is to restart the interpreter. Alternatively, you can manually remove the assignment using:
del str
Remember that str is not a defined global variable by default; it is typically found in the builtins module that gets imported upon Python startup.
The above is the detailed content of Why Does Redefining the Built-in `str` Function Lead to a TypeError in String Conversion?. For more information, please follow other related articles on the PHP Chinese website!