[Tutor] When are "__init__.py" files needed and not needed in a project?

Peter Otten __peter__ at web.de
Sat Oct 20 14:35:46 EDT 2018

boB Stepp wrote:

> Linux Mint 19 Cinnamon, Python 3.6.6
> I would have sworn that I had read, either on this list or the main
> Python list, that in the most recent versions of Python 3 that
> "__init__.py" files were no longer needed in nested project file
> structures.  

If you omit the __init__.py you get a "namespace package".

Namespace packages can combine multiple directories into one package, but 
will be shaded by "normal" packages.

> But when I attempted to run tests for the first time on
> my new Solitaire Scorekeeper project (Finally getting around to
> this!), I got:
> bob at Dream-Machine1:~/Projects/solitaire_scorekeeper$ python3 -m unittest
> ----------------------------------------------------------------------
> Ran 0 tests in 0.000s
> OK
> So no tests were run.  So it immediately occurred to me to add an
> empty "__init__.py" file to my "tests" subfolder and got what I was
> currently expecting:
> bob at Dream-Machine1:~/Projects/solitaire_scorekeeper$ python3 -m unittest
> E
> ======================================================================
> ERROR: test_get_gamenames_bad_path
> (tests.tests_main.TestGameNamesMapperMethods) Test that when the method,
> get_gamenames(), is passed a path to a
> ----------------------------------------------------------------------
> Traceback (most recent call last):
>   File "/home/bob/Projects/solitaire_scorekeeper/tests/tests_main.py",
> line 20, in test_get_gamenames_bad_path
>     self.assertEqual(gamenames.gamenames(), {})
> NameError: name 'self' is not defined
> ----------------------------------------------------------------------
> Ran 1 test in 0.000s
> FAILED (errors=1)
> I was expecting this error and will shortly correct it.  So my
> question remains, when are "__init__.py" files needed and when are
> they not?

I am struggling with the differences between the two types of packages 
myself, so my first guess was that you accidentally found out that test
discovery doesn't work for namespace packages. However


expicitly states

Changed in version 3.4: Test discovery supports namespace packages.

Perhaps you should file a bug report.

> In case it helps, my current project structure is:
> ~/Projects
>     data/
>     docs/
>     tests/
>     .git/
>     main.py
>     .gitignore
> TIA!

More information about the Tutor mailing list