Shital Shah
Shital Shah

Reputation: 68868

Best practises for imports in Python 3 packages and scripts

Consider this simple folder structure:

root
  Package1
    x.py
    y.py
  Package2
    z.py
  Examples
    main.py

Now our requirements are:

Below is what works:

x.py

import y

def x():
  y()

y.py

def y():
  pass

z.py

import package1.y as y

def z():
  y.y()

main.py

import sys
from os import path
sys.path.append(  path.dirname(  path.dirname( path.abspath(__file__) ) ) )

import package1.y as y
import package2.z as z

y.y()
z.z()

Questions:

  1. Is this the best and recommended way to setup imports in Python 3?
  2. I really don't like changing sys.path in main because it strongly binds assumptions about package locations inside code file. Is there any way around that?
  3. I also really don't like superfluous as y part in import package1.y as y. Is there any way around that?

Upvotes: 3

Views: 318

Answers (1)

Davis Herring
Davis Herring

Reputation: 40023

As always, there are two separate steps:

  1. You write the code against the abstract namespace of packages, which contains package1 and package2 (and sys, os, etc.), but not “Examples” which is not a package (because main.py is not a module).
  2. You set sys.path appropriately before any of your code ever runs. If it's your own (uninstalled) code, there are places you can put it, or you can write an easy shell script wrapper to set PYTHONPATH for your python process.

So the answers to your questions are

  1. In x.py you write from . import y. (Python 2 supports this and 3 requires it.)
  2. How you set sys.path depends on your packaging/environment system. The traditional way is to set the PYTHONPATH environment variable for the python process, but there are other ways involving things like the site module.
  3. from package1 import y is the usual way to name things only once.

Upvotes: 1

Related Questions