By Joril

2008-09-16 14:24:02 8 Comments

Imagine this directory structure:


I'm coding mod1, and I need to import something from mod2. How should I do it?

I tried from ..sub2 import mod2 but I'm getting an "Attempted relative import in non-package".

I googled around but found only "sys.path manipulation" hacks. Isn't there a clean way?

Edit: all my's are currently empty

Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (sub1, subX, etc.).

Edit3: The behaviour I'm looking for is the same as described in PEP 366 (thanks John B)


@Giorgos Myrianthous 2020-03-25 10:13:17

You have to append the module’s path to PYTHONPATH:

export PYTHONPATH="${PYTHONPATH}:/path/to/your/module/"

@Joril 2020-03-25 14:50:20

This is roughly the same as manipulating sys.path, since sys.path gets initialized from PYTHONPATH

@Giorgos Myrianthous 2020-03-25 14:51:16

@Joril That's correct but sys.path needs to be hardcoded in the source code in contrast to PYTHONPATH which is an environment variable and can be exported.

@Роман Арсеньев 2016-02-11 12:01:50

This is solved 100%:

  • app/
  • settings/

Import settings/ in app/

import sys
sys.path.insert(0, "../settings")

    from local_settings import *
except ImportError:
    print('No Import')

@Vit Bernatik 2016-11-04 20:22:39

thank you! all ppl were forcing me to run my script differently instead of telling me how to solve it within script. But I had to change the code to use sys.path.insert(0, "../settings") and then from local_settings import *

@Thomas 2020-07-17 16:33:24

Sorry, but the sys.path hacks are definitely a good way to solve this. Yes it works, but if you look at other SO threads about sys.path hacks you'll quickly see why this isn't recommend more.

@LondonRob 2015-06-09 15:22:27

As @EvgeniSergeev says in the comments to the OP, you can import code from a .py file at an arbitrary location with:

import imp

foo = imp.load_source('', '/path/to/')

This is taken from this SO answer.

@John B 2008-09-16 14:48:56

Everyone seems to want to tell you what you should be doing rather than just answering the question.

The problem is that you're running the module as '__main__' by passing the as an argument to the interpreter.

From PEP 328:

Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

In Python 2.6, they're adding the ability to reference modules relative to the main module. PEP 366 describes the change.

Update: According to Nick Coghlan, the recommended alternative is to run the module inside the package using the -m switch.

@Nick Retallack 2010-05-11 04:27:28

The answer here involves messing with sys.path at every entry point to your program. I guess that's the only way to do it.

@ncoghlan 2011-02-23 04:25:29

The recommended alternative is to run modules inside packages using the -m switch, rather than by specifying their filename directly.

@Tom 2012-09-29 16:34:55

I don't understand: where is the answer here? How can one import modules in such a directory structure?

@Xiong Chiamiov 2012-11-20 06:06:41

@Tom: In this instance, mod1 would from sub2 import mod2. Then, to run mod1, from within app, do python -m sub1.mod1.

@LarsH 2013-01-29 16:58:57

@XiongChiamiov: does this mean you can't do it if your python is embedded in an application, so you don't have access to python command line switches?

@Alexey Kuzminich 2013-04-25 05:12:35

@MattJoiner: It works if you run as python -m app.sub1.mod1 (from the parent dir of app) as Pankaj wrote.

@x-yuri 2017-12-29 14:08:50

To make it clear, when you do from .m import whatever in a script you pass as an argument to interpreter, it basically resolves to from __main__.m import whatever. Which makes it look for __main__/

@jpmc26 2019-04-03 03:52:50

"Everyone seems to want to tell you what you should be doing rather than just answering the question." Well, good. That's the way getting help writing software should be! When I fly in the face of good practice, I want to know.

@suhailvs 2013-12-08 03:19:42

explanation of nosklo's answer with examples

note: all files are empty.
app/ ->
    package_a/ ->
    package_b/ ->


def print_a():
    print 'This is a function in dir package_a'


from app.package_a.fun_a import print_a
def print_b():
    print 'This is a function in dir package_b'
    print 'going to call a function in dir package_a'
    print '-'*30

from app.package_b import fun_b

if you run $ python it returns:

This is a function in dir package_b
going to call a function in dir package_a
This is a function in dir package_a
  • does: from app.package_b import fun_b
  • does from app.package_a.fun_a import print_a

so file in folder package_b used file in folder package_a, which is what you want. Right??

@lesnik 2011-11-19 16:05:29

"Guido views running scripts within a package as an anti-pattern" (rejected PEP-3122)

I have spent so much time trying to find a solution, reading related posts here on Stack Overflow and saying to myself "there must be a better way!". Looks like there is not.

@jfs 2013-04-29 00:14:30

Note: Already mentioned pep-366 (created around the same time as pep-3122) provides the same capabilities but uses a different backward-compatible implementation i.e., if you want to run a module inside a package as a script and use explicit relative imports in it then you could run it using -m switch: python -m app.sub1.mod1 or invoke app.sub1.mod1.main() from a top-level script (e.g., generated from setuptools' entry_points defined in

@RecencyEffect 2020-03-11 11:51:57

+1 for using setuptools and entry points - it is a proper way to set up scripts that will be run from the outside, in a well-defined location, as opposed to endlessly hacking PYTHONPATH

@Pankaj 2013-03-17 07:43:34

Here is the solution which works for me:

I do the relative imports as from ..sub2 import mod2 and then, if I want to run then I go to the parent directory of app and run the module using the python -m switch as python -m app.sub1.mod1.

The real reason why this problem occurs with relative imports, is that relative imports works by taking the __name__ property of the module. If the module is being directly run, then __name__ is set to __main__ and it doesn't contain any information about package structure. And, thats why python complains about the relative import in non-package error.

So, by using the -m switch you provide the package structure information to python, through which it can resolve the relative imports successfully.

I have encountered this problem many times while doing relative imports. And, after reading all the previous answers, I was still not able to figure out how to solve it, in a clean way, without needing to put boilerplate code in all files. (Though some of the comments were really helpful, thanks to @ncoghlan and @XiongChiamiov)

Hope this helps someone who is fighting with relative imports problem, because going through PEP is really not fun.

@MestreLion 2013-11-07 03:40:14

Best answer IMHO: not only explains why OP had the issue, but also finds a way to solve it without changing the way his modules do imports. Afterall, OP's relative imports were fine. The culprit was the lack of access to outer packages when directly running as script, something -m was designed to solve.

@JeremyKun 2014-04-01 21:05:51

Also take note: this answer was 5 years after the question. These features were not available at the time.

@Rotareti 2016-09-16 23:47:53

If you want to import a module from the same directory you can do from . import some_module.

@milkypostman 2013-01-07 04:26:52

Let me just put this here for my own reference. I know that it is not good Python code, but I needed a script for a project I was working on and I wanted to put the script in a scripts directory.

import os.path
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

@Gabriel 2012-09-11 07:47:16

On top of what John B said, it seems like setting the __package__ variable should help, instead of changing __main__ which could screw up other things. But as far as I could test, it doesn't completely work as it should.

I have the same problem and neither PEP 328 or 366 solve the problem completely, as both, by the end of the day, need the head of the package to be included in sys.path, as far as I could understand.

I should also mention that I did not find how to format the string that should go into those variables. Is it "package_head.subfolder.module_name" or what?

@Andrew_1510 2012-03-17 09:20:09

I found it's more easy to set "PYTHONPATH" enviroment variable to the top folder:



import sub1.func1
#...more import

of course, PYTHONPATH is "global", but it didn't raise trouble for me yet.

@byxor 2017-09-09 01:13:11

This is essentially how virtualenv lets you manage your import statements.

@Garrett Berg 2012-03-02 22:58:47

This is unfortunately a sys.path hack, but it works quite well.

I encountered this problem with another layer: I already had a module of the specified name, but it was the wrong module.

what I wanted to do was the following (the module I was working from was module3):


import mymodule.mymodule1.mymodule1_1  

Note that I have already installed mymodule, but in my installation I do not have "mymodule1"

and I would get an ImportError because it was trying to import from my installed modules.

I tried to do a sys.path.append, and that didn't work. What did work was a sys.path.insert

if __name__ == '__main__':
    sys.path.insert(0, '../..')

So kind of a hack, but got it all to work! So keep in mind, if you want your decision to override other paths then you need to use sys.path.insert(0, pathname) to get it to work! This was a very frustrating sticking point for me, allot of people say to use the "append" function to sys.path, but that doesn't work if you already have a module defined (I find it very strange behavior)

@Nister 2016-11-05 09:13:15

sys.path.append('../') works fine for me (Python 3.5.2)

@Tom Russell 2017-12-01 00:54:21

I think this is fine since it localizes the hack to the executable and doesn't affect other modules which may depend on your packages.

@jung rhew 2011-06-29 17:33:27

From Python doc,

In Python 2.5, you can switch import‘s behaviour to absolute imports using a from __future__ import absolute_import directive. This absolute- import behaviour will become the default in a future version (probably Python 2.7). Once absolute imports are the default, import string will always find the standard library’s version. It’s suggested that users should begin using absolute imports as much as possible, so it’s preferable to begin writing from pkg import string in your code

@mossplix 2011-09-24 19:31:57

Take a look at You could do

from .mod1 import stuff

@PuercoPop 2013-04-03 18:04:10

Except one can't do relative imports from the 'main' module as the answer from John B. states

@iElectric 2009-07-04 23:27:50

def import_path(fullpath):
    Import a file with full path specification. Allows one to
    import from anywhere, something __import__ does not do. 
    path, filename = os.path.split(fullpath)
    filename, ext = os.path.splitext(filename)
    module = __import__(filename)
    reload(module) # Might be out of date
    del sys.path[-1]
    return module

I'm using this snippet to import modules from paths, hope that helps

@Xiong Chiamiov 2009-07-16 21:20:00

I'm using this snippet, combined with the imp module (as explained here [1]) to great effect. [1]:…

@Alex Che 2010-06-16 08:24:57

Probably, sys.path.append(path) should be replaced with sys.path.insert(0, path), and sys.path[-1] should be replaced with sys.path[0]. Otherwise the function will import the wrong module, if there is already a module with the same name in search path. E.g., if there is "" in current dir, import_path("/imports/") will import the wrong file.

@iElectric 2010-06-19 07:13:36

I agree! Sometimes other relative imports will make precedance. Use sys.path.insert

@levesque 2010-12-07 19:26:59

How would you replicate the behavior of from x import y (or *)?

@mrgloom 2018-09-24 13:12:19

It's not clear, please specify full usage of this script to solve OP problem.

@nosklo 2009-01-21 12:42:11
app/ ->
    package_a/ ->
    package_b/ ->
  1. You run python
  2. does: import app.package_a.module_a
  3. does import app.package_b.module_b

Alternatively 2 or 3 could use: from app.package_a import module_a

That will work as long as you have app in your PYTHONPATH. could be anywhere then.

So you write a to copy (install) the whole app package and subpackages to the target system's python folders, and to target system's script folders.

@auraham 2012-07-27 16:34:33

Excellent answer. Is there some way to import that way without install the package in PYTHONPATH?

@nosklo 2013-10-17 11:40:31

@Spybdai 2016-12-16 11:30:04

then, one day, need to change name of app to test_app. what would happen? You will need to change all the source codes, import app.package_b.module_b --> test_app.package_b.module_b. this is absolutely BAD practice... And we should try to use relative import within the package.

Related Questions

Sponsored Content

30 Answered Questions

[SOLVED] How to import a module given the full path?

26 Answered Questions

[SOLVED] Does Python have a ternary conditional operator?

12 Answered Questions

[SOLVED] Relative imports in Python 3

28 Answered Questions

[SOLVED] Importing files from different folder

44 Answered Questions

22 Answered Questions

[SOLVED] What are metaclasses in Python?

42 Answered Questions

[SOLVED] How to get the current time in Python

  • 2009-01-06 04:54:23
  • user46646
  • 3369278 View
  • 2970 Score
  • 42 Answer
  • Tags:   python datetime time

39 Answered Questions

[SOLVED] How do I check whether a file exists without exceptions?

61 Answered Questions

[SOLVED] Calling an external command from Python

10 Answered Questions

[SOLVED] Does Python have a string 'contains' substring method?

Sponsored Content