[New-bugs-announce] [issue46635] unittest.defaultTestLoader.discover fails for namespace packages

Tasos Papastylianou report at bugs.python.org
Fri Feb 4 06:35:56 EST 2022

New submission from Tasos Papastylianou <tpapastylianou at hotmail.com>:

Back in python 3.6.9, attempting to import __file__ on a namespace package resulted in an attribute error. From at least 3.8 onwards, this behaviour seems to have changed, and __file__ simply returns None instead.

This seems to have broken unittest discovery. Looking at the code, it seems that discover still seems to rely on a try/except block in order to test for a namespace package. Now that the attribute error is no longer present in later python versions, discover simply accepts the None value for __file__, and fails further down the line when attempting to canonicalise a path containing a None value (error effectively expects a string).

On my system with python 3.8, the relevant files/lines are:

- /usr/lib/python3.8/unittest/loader.py()discover()
  The try block starting at line 304 checks for the module's __file__ attribute, expecting to redirect to 307 to "look for namespace packages" in case of an attribute error. Obviously, now that __file__ returns None instead, this logic fails.

- The call to dirname in line 306 therefore proceeds normally, passing a None as a file, which then fails with a TypeError: expected str, bytes or os.PathLike object, not NoneType

See https://github.com/tpapastylianou/self-contained-runnable-python-package-template/issues/13# for the example in the wild that prompted the discovery of this bug.

components: Tests
messages: 412505
nosy: tpapastylianou
priority: normal
severity: normal
status: open
title: unittest.defaultTestLoader.discover fails for namespace packages
type: behavior
versions: Python 3.10, Python 3.8, Python 3.9

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list