Python imports and unit tests

Viewed 67

I am trying to build a Python package/library for the first time. So far I have these files:

src
  Accentizer2
    __init__.py
    Accentizer.py
    Annotation.py
test
  test_1.py

File contents:

Accentizer.py:

from Annotation import Annotation # this is where the error occurs


class Accentizer:
    x = 10

Annotation.py:

class Annotation:
    Variants = []

test_1.py:

from src.Accentizer2.Accentizer import Accentizer

When I run test_1.py, I get the following error:

Traceback (most recent call last):
  File "..\tests\test_1.py", line 1, in <module>
    from src.Accentizer2.Accentizer import Accentizer
  File "..\src\Accentizer2\Accentizer.py", line 1, in <module>
    from Annotation import Annotation
ModuleNotFoundError: No module named 'Annotation'

When I run Accentizer.py, it runs ok.

What am I missing? What is the conventional way of linking tests to code under test?

Changing the import statement in Accentizer.py to the line below fixes the error:

from src.Accentizer2.Accentizer import Accentizer

But then I get the error 'src is not a module name' after I build and install the Accentizer2 package and try to import it in another project.

1 Answers

Several things are a little off in here

Current problem

in your Accentizer.py you are trying to import a global package Annotation. However, the Annotation.py is a local file (local to the package/folder).

Assuming your src folder is in the sys.path, a correct way of doing it (given your folder structure) is either have a global or local import. Note: the names global and local are not really standard :)

Global import

This just imports the package, and provides a fully qualified path during import. Assumption is that src is in the path.

from src.Accentizer2.Annotation import Annotation

class Accentizer:
    x = 10

Local import

This one doesn't care about where everything is located, and uses . to refer to the current folder. You can also use .. to refer to parent, ... to grandparent, etc.

from .Annotation import Annotation

class Accentizer:
    x = 10

Stylistic problems

src folder

It is non-pythonic to have a src folder. It is customary for a lot of languages, but not some much for python

Naming convention

Generally, you don't wanna name the files the same as the class names. I would suggest having files accentizer.py and annotation.py with classes Accentizer and Annotation respectively. The reasoning is that having the same name for class and file might break the import process.

Related