4

I'm developing a python framework and want to do imports based on the top-level package (the project name). Users will use the framework by copying the entire framework and writing their own modules within.

My current structure looks like this:

myapp/
  config.py
  docs/
  framework/
    main.py
    utils.py
  file.py
  lib/
    some_module.py
  unit_tests/
    test_utils.py

I want to be able to use the following import in python files in lib and unit_tests in the following way:

from myapp.framework import utils

Is there a simple way to do this? I've tried doing sys.path.append() hacks but they don't really work. If there is a truly pythonic way to achieve this, I don't mind going extra lengths to get it working.

EDIT: Well I tried the sys.path.append() again and it actually works but it really is an in-elegant solution and I'd really like to hear if there's another way.

trinth
  • 5,919
  • 9
  • 40
  • 45

1 Answers1

2

For short: You can't have two modules with the same name one inside the other. You have the myapp folder and the myapp.py file

That's because of the order of importing modules.

  1. Inside the current directory
  2. The current package
  3. Global package folder

So, if you're trying to import myapp.lib.some_module in config.py the interpreter will first see that you have myapp.py in the same folder and literaly try to import lib.some_module from that file, which doesn't exist.

Would be something as trying to import myapp.myapp.lib.some_module from outside that module.

So, the best thing for you to do is to rename the myapp.py file

JBernardo
  • 32,262
  • 10
  • 90
  • 115
  • Oops sorry, the myapp.py file was supposed to be a placeholder file to show that there's other files. It's not actually present in the framework. I'll edit it out of the question. – trinth May 20 '11 at 05:33