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\", line 5, in <module>
    import sort
  File "C:\Users\massi\Documents\OU\", line 11, in <module>
    from .priority_queue import PriorityQueue
ValueError: Attempted relative import in non-package
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:  # a script using your 'modules'
mysort/  # a directory for the package mysort implemented by you
mysort/  # an empty python file, that marks the mysort dir as a package directory
mysort/   # your implementtation of priority queue
mysort/ # contains the implementation of quick_sorted()

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

Open in new window

in  mysort/

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 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 Modules and Packages
Massimo ScolaAuthor Commented:
Great this worked fine for me.
Thanks a lot
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.