Error when importing Python module: ValueError: Attempted relative import in non-package

I am learning Python and I need some help with this:

I understand that that in order to import, I write from x import y.  In my example, I am trying to import quick_sorted from sort.
Both files are in the same folder.

The quick_sort method relies on code which is in the priority queue file.
Interestingly, it is imported this way:
from .priority_queue import PriorityQueue

Open in new window

The files to import are supplied for me to use.

Is there anything wrong with my implementation or with the files supplied?

I import it the following way:

from sort import quick_sorted

Open in new window


I am trying to use the quick sort method so that I can sort one of my lists.

This is the error I get:

Traceback (most recent call last):
  File "C:\Users\massi\Documents\OU\TMA02_Q2.py", line 5, in <module>
    import sort
  File "C:\Users\massi\Documents\OU\sort.py", line 11, in <module>
    from .priority_queue import PriorityQueue
ValueError: Attempted relative import in non-package

TMA02_Q2.py
sort.py
priority_queue.py
Massimo ScolaAsked:
Who is Participating?
 
gelonidaConnect With a Mentor Commented:
Just write :
from priority_queue import PriorityQueue

Open in new window


This should work.

from .<name> import 

Open in new window

is a relative import that works only for packages and not for top level directories.



let's imagine following directory structure:

your_main_script.py  # a script using your 'modules'
mysort/  # a directory for the package mysort implemented by you
mysort/__init__.py  # an empty python file, that marks the mysort dir as a package directory
mysort/priority_queue.py   # your implementtation of priority queue
mysort/quick_sort.py # contains the implementation of quick_sorted()

in this case you would write in
your_main_script.py
from mysort.quick_sort import quick_sorted

Open in new window



in  mysort/quick_sort.py

you could now write either of two following import statements:
from mysort.priority_queue import PriorityQueue  # this is an absolute import
from .priority_queue import PriorityQueue # this is a relative import as quick_sort.py is in the same package directory as priority_queue,py

Open in new window


On a top level directory you cannot perform relativ imports ( imports starting with a '.' )

Hope that clarifies a little.
You might want to look at Learnpython.org Modules and Packages
0
 
Massimo ScolaAuthor Commented:
Great this worked fine for me.
Thanks a lot
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.