Home > Backend Development > Python Tutorial > What Happens When Your Python Script's Name Conflicts with an Imported Library?

What Happens When Your Python Script's Name Conflicts with an Imported Library?

DDD
Release: 2024-12-28 12:12:15
Original
422 people have browsed it

What Happens When Your Python Script's Name Conflicts with an Imported Library?

Importing a Library with the Same Name as the Script

When you name your script with the same name as an imported library, such as for instance requests.py, various import issues can arise. These issues can manifest as AttributeErrors, ImportErrors, or NameErrors depending on the import approach used.

This occurs because the script's name shadows the installed library in sys.path, giving precedence to the local script over the intended import.

Symptoms

Plain Import

import requests

res = requests.get('http://www.google.ca')
print(res)
Copy after login
  • Error: AttributeError: module 'requests' has no attribute 'get'

Specific Import from Name

from requests import get

res = get('http://www.google.ca')
print(res)
Copy after login
  • Error: ImportError: cannot import name 'get'

Module Import from Package

from requests.auth import AuthBase
Copy after login
  • Error: ImportError: No module named 'requests.auth'; 'requests' is not a package

Star Import

from requests import *

res = get('http://www.google.ca')
print(res)
Copy after login
  • Error: NameError: name 'get' is not defined

Solution

To resolve this issue, rename your script to a different name that does not conflict with any imported modules. Additionally, delete the generated requests.pyc file (if present) to prevent interference from the cached bytecode.

Traceback Debugging

When encountering these errors, examine the traceback carefully to identify the module name collision between the script name and the imported module.

The above is the detailed content of What Happens When Your Python Script's Name Conflicts with an Imported Library?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template