Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does unittest require __init__.py to be present in Python 3.6?

I just come across this line in python3.6 unittest (/usr/lib/python3.6/unittest/loader.py:286):

is_not_importable = not os.path.isfile(os.path.join(start_dir, '__init__.py'))

which caused the unittest discovery to fail to run my tests. Why is this line still present in python3.6 library (Ubuntu 17.10, I don't know if it matters), if __init__.py is no longer required since python3.3?

I believe that's a bug, but I want a confirmation.

When there's no __init__.py in the foo directory, the following command runs fine ({PROJECT_HOME} being a placeholder):

python3.6 -m unittest discover tests.foo -t {PROJECT_HOME} -p "*.py"

while this fails (with ImportError: Start directory is not importable):

python3.6 -m unittest discover tests/foo -t {PROJECT_HOME} -p "*.py"

The difference being . -> / When there is __init__.py, both commands work the same.

like image 767
John Doe Avatar asked Jan 30 '26 15:01

John Doe


1 Answers

My best guess is that the . means you are importing it as a submodule, whereas the / means you are importing it as a path. If you import it as a submodule, then it's loading the module above it. If you're importing it as a path, it won't like that because you're trying to import something that's part of a module directly

like image 136
Olivia A Avatar answered Feb 02 '26 05:02

Olivia A