1

I have a package with the following hierarchy

my_package/__init__.py
           script_a.py
           scripts_dir/__init__.py
                       script_b.py
           my_package/__init__.py
                      module_a.py
                      module_b.py

module_a and module_b contain function and class definitions that I am using in script_a and script_b (which are stand alone scripts and contain a main)

When I import something from let's say module_a.py in my script_a.py everything is fine.

My problems are

  • I cannot figure out how to use relative imports to import something from module_a or module_b to script_b.py
  • I am not sure if I am supposed to use relative imports or if it makes more sense to add my_package to sys.path and then use something like from my_package.module_a import the_funky_func

  • I want to avoid having to call the interpreter with the -m argument

update

From the answers I have found so far in SO I have concluded that I have 3 options

  • write a setup to include the package to my PYTHONPATH so that all scripts regardless of where they are can call the modules

  • use the -m argument when invoking the interpreter

  • do some sys.path hack

Is there another option that I am not aware of?

LetsPlayYahtzee
  • 7,161
  • 12
  • 41
  • 65
  • for the last part you can check my solution to that: [how-to-use-relative-import-without-doing-python-m](http://stackoverflow.com/questions/35855800/how-to-use-relative-import-without-doing-python-m) – Copperfield Apr 24 '16 at 20:25

1 Answers1

0
myproject/
        |--package1
              |--\__init__.py
              |--script_a.py
              |--script_b.py
        |--package2
              |--module_a.py
              |--module_b.py

You can use below 2 lines appends myproject path to sys path. It can avoid relative import and avoid -m in the command line

import sys
import sys.path.append("/absolute/path/to/your/myproject")

In myproject file script_a.py, if you import module_a.py it would look like

import sys
import sys.path.append("/absolute/path/to/your/myproject")
import package2.module_a as ma
Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125