0

The following simple script raises an ImportError in python3:

from multiprocessing import Queue
queue = Queue()
print("OK")

The key to reproduce this error is to name this file queue.py, and then the following messages appear:

Traceback (most recent call last):
File "queue.py", line 3, in <module>
    queue = Queue()
File "/home/wangc/app/anaconda/lib/python3.5/multiprocessing/context.py", line 100, in Queue
    from .queues import Queue
File "/home/wangc/app/anaconda/lib/python3.5/multiprocessing/queues.py", line 20, in <module>
    from queue import Empty, Full
File "/home/wangc/temp/queue.py", line 3, in <module>
    queue = Queue()
File "/home/wangc/app/anaconda/lib/python3.5/multiprocessing/context.py", line 100, in Queue
    from .queues import Queue
ImportError: cannot import name 'Queue'

If the file is named as queueue.py, then everything is fine.

I think this is because multiprocessing module is trying to import Queue from my queue.py since its name coincides with some file in multiprocessing module.

However, If it is how python works, then I should avoid filenames of any possible internal libraries, which is not practical.

Is this error attributed to the same filename of my file and some file in multiprocessing module? And if it is, how can I ensure my filenames are distinct from files of any possible library in general programming?

atbug
  • 818
  • 6
  • 26
  • 1
    The `Queue` actually comes from the `queue` package in the standard lib. – Klaus D. Feb 13 '17 at 03:58
  • This is indeed how python works - check out http://stackoverflow.com/questions/1224741/trying-to-import-module-with-the-same-name-as-a-built-in-module-causes-an-import – daveruinseverything Feb 13 '17 at 04:01
  • Then I should avoid names of any possible library. How can I do that? – atbug Feb 13 '17 at 04:03
  • It's only modules you've written that are on the module search path that can be problematic. If you put your modules into packages, then only the package name is at risk of colliding with something. – Blckknght Feb 13 '17 at 04:07

1 Answers1

2

You can't have the same file name as the module you are importing. Read modules for more clarification Using that, any unadorned package name will always refer to the top level package. You will then need to use relative imports to access your own package. You will want to read about Absolute and Relative Imports which addresses this very problem.

khushbu
  • 158
  • 11