Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Created April 4, 2013 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joyrexus/5314312 to your computer and use it in GitHub Desktop.
Save joyrexus/5314312 to your computer and use it in GitHub Desktop.
Relative imports for non-package files.
import sys
sys.path.insert(0, '..') # relative path to MODULE, change as appropriate
from MODULE import * # replace MODULE with the name of your module

Intra-package referencing for scripts

Situation

You want to keep your demo/test scripts within your package directory; the module your demo/test-ing is not in the PYTHONPATH or default sys.path.

Background

A module within a package can use relative imports (importing other package modules relative to the importing modules location). This is known as intra-package referencing. However, this doesn't apply to files that you happen to place within a package that are designed to be run as scripts, where the aim is to test or demo the package.

Solution

At the top of your intra-package demo/test scripts, append the appropriate relative path to sys.path.

For example, suppose you want to demo your custom sets.py module with some scripts from a demo subdirectory:

.
├── __init__.py
├── demo
│   ├── poset.py
│   ├── recur.py
│   ├── relation.py
│   └── zorn.py
└─── sets.py

Create a file called package.py and add it to the demo subdir. It should contain ...

import sys
sys.path.insert(0, '..')
from sets import *

Now, import everything from package.py within your demo scripts. For example:

from __future__ import division
from package import *

X = Set([(x, y) for x in range(-3, 4) for y in range(-3, 4)])

def z(x, y):
    return (2*x + 1) / 2**y

cond = lambda a, b: z(*a) <= z(*b)

R = X.relation(cond)

assert len(R) == 1225
assert R.reflexive
assert not R.symmetric
assert R.transitive
assert R.antisymmetric
assert R.partial_order
assert not R.total_order
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment