How to accomplish relative import in Python


   wants to import

This is just an example, but really I just want to do a relative import of a module in a parent directory. I've tried various things and get this error...

Attempted relative import beyond toplevel package

I read somewhere that the script from where the program starts shouldn't reside in the package, and I tried modifying the structure for that like so...

stuff/ // Equivalent of in above

But I got the same error.

How can I accomplish this? Is this even an adequate approach?

In Python 2.


  • After fiddling with it a bit more, I realized how to set it up, and for the sake of specificity I won't use foo bar names. My project directory is set up as...

                # files that need to use
       # see example at bottom
                # files that need to use
   # core is the top level package
        LICENSE # equivalent to for the state editor # equivalent to for the object editor

    A line in looks like...

    from core.object_editor import editor

    A line in looks like...

    from .. import ntlib

    or alternatively

    from core import ntlib

    The key is that in the example I gave in the question, the "main" script was being run from within the package. Once I moved it out, created a specific package (core), and moved the library I wanted the editors to share (ntlib) into that package, everything was hunky-dory.