nosetests vs. relative imports?

Roy Smith roy at panix.com
Tue Dec 24 21:12:35 EST 2013


Environment:
Ubuntu Linux 12.04 (precise)
Python 2.7.3

I have a package (i.e. a directory with a __init__.py file).  In that 
directory, I have files math.py and test_math.py; test_math.py contains 
the single line:

from .math import EMA

If I run on the command line, "nosetests test_math.py" everything is 
fine (it reports "Ran 0 tests in 0.001s", which is what I expect, since 
I haven't written any tests yet).

But, if I leave off the .py, I get:

$ nosetests test_math
E
======================================================================
ERROR: Failure: ValueError (Attempted relative import in non-package)
----------------------------------------------------------------------
Traceback (most recent call last):
  File 
"/home/roy/deploy/current/python/local/lib/python2.7/site-packages/nose/l
oader.py", line 413, in loadTestsFromName
    addr.filename, addr.module)
  File 
"/home/roy/deploy/current/python/local/lib/python2.7/site-packages/nose/i
mporter.py", line 47, in importFromPath
    return self.importFromDir(dir_path, fqname)
  File 
"/home/roy/deploy/current/python/local/lib/python2.7/site-packages/nose/i
mporter.py", line 94, in importFromDir
    mod = load_module(part_fqname, fh, filename, desc)
  File "/home/roy/deploy/current/code/songza/util/test_math.py", line 1, 
in <module>
    from .math import EMA
ValueError: Attempted relative import in non-package

----------------------------------------------------------------------
Ran 1 test in 0.001s


What is going on that nose can't deal with the relative import when run 
that way?

Nose has always felt like a magic ring.  I'm really glad I discovered it 
because it makes my life so much better.  But I'm never quite sure I 
really understand everything it's doing.



More information about the Python-list mailing list