Script name same as imported module name

501 views Asked by At

If you have a script like:

import requests
requests.get()

and you name it requests.py you will get an attribute error saying that requests has no attribute get because Python is referring to the script name requests and that name doesn't have an attribute get.

However, if I have this script:

import time
time.sleep()

and I name it time.py, there won't be any error. Tried both on Python 2.7.11 and Python 3.5.3.

Why doesn't the same rule apply here?

1

There are 1 answers

0
Jean-François Fabre On BEST ANSWER

because time is built-in, and request is a site package:

Try printing the __file__ attribute to see where the module is located:

print(time.__file__)
AttributeError: 'module' object has no attribute '__file__'

you get an error, but with requests you get the answer

print(requests.__file__)
C:\Python34\lib\site-packages\requests\__init__.py

another hint is given by help(time.__loader__):

>>> help(time.__loader__)
Help on class BuiltinImporter in module importlib._bootstrap:

class BuiltinImporter(builtins.object)
 |  Meta path import for built-in modules.

for requests:

>>> help(requests.__loader__)
Help on SourceFileLoader in module importlib._bootstrap object:

class SourceFileLoader(FileLoader, SourceLoader)
 |  Concrete implementation of SourceLoader using the file system.

Anyway, don't call your modules as built-ins or library packages. In both cases you'll have problems.

  • naming after a built-in: you cannot import it, as you saw
  • naming after a site package: you cannot import the site package/use it in your module