Take the 2-minute tour ×

I have several python modules in a directory.

In the same directory, I have a package tests.

I would quite like to name the modules in tests the same as the modules that they contain tests for, although of course it isn't critical.

So, in tests.foo I naively write import foo. This isn't working so well - it imports tests.foo, not top-level foo.

Can I do what I want, or do I just have to call the test module test_foo?

Sorry if this is obvious or a dupe, my search-fu has failed.

share|improve this question

2 Answers 2

up vote 4 down vote accepted

test_foo.py seems like an appropriate solution in this case.

If you don't rename the test modules then make the tests directory into Python package (add tests/__init__.py file) and use absolute imports:

from __future__ import absolute_import 
import foo                   # import global foo.py, the first foo.py in sys.path
import tests.foo as test_foo # import tests/foo.py
share|improve this answer

Use the full package path like this:

   |-- __init__.py
   |-- foo.py
   |-- tests
   |    | -- __init__.py
        | -- foo.py

in tests/foo.py do

from Package import foo

And i think this part of the documentation can interest you : http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports

share|improve this answer
Thanks, but "ValueError: Attempted relative import beyond toplevel package". This is Python 2.6, if it makes any difference. You're probably right that I should have put everything in a top-level package in the first place. I'm uncertain if that change now would be painless. –  Steve Jessop Jan 27 '11 at 13:48
@Steve Jessop: sorry i meant use the full package path to import the foo module, i edit it i hope now it's clear –  mouad Jan 27 '11 at 14:16

Your Answer


