python / python/cpython

`__module__` is not defined, seeming to contradict the Python Data Model.

Open
#120,857 13 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

type-bug
Dominant language
Python
Stars
77.2k
Forks
36k
PR merge metrics
PR metrics pending

Description

Bug report

Bug description:

The __module__ variable might not be defined.

This is an update to the original bug post. After some investigation this doesn't seem like a bug in unittest. Here's a simple test case that shows a situation where __module__ is not defined:

test_str = """
class MyClass:
    pass

Derived = type("Derived", (MyClass,), {})
"""

test_ns = {}
exec(test_str, test_ns)
print("__module__ exists:", hasattr(test_ns["Derived"], "__module__"))
print("Module for drived:", test_ns["Derived"].__module__)

The original bug post is below:

https://github.com/python/cpython/blob/03fa2df92707b543c304a426732214002f81d671/Lib/unittest/loader.py#L220

The default test loader depends on __module__ being present. In rare cases it may not be. I encountered a crash when running unit tests using a Jupyter cell magic. The line should probably be:

            fullName = f'%s.%s.%s' % (
                testCaseClass.__module__ if hasattr(testCaseClass, "__module__") else "None", testCaseClass.__qualname__, attrname
            )

This problem has cropped up in bug reports for other projects. For example:

https://github.com/ray-project/ray/issues/4758
https://gitlab.orekit.org/orekit-labs/python-wrapper/-/issues/411

Thank you for the wonderful work!

CPython versions tested on:

3.12

Operating systems tested on:

Linux

Linked PRs
  • gh-120957
  • gh-120979

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at Lib/unittest/loader.py#L220 and run the provided exec reproduction on Python 3.12. Check the default test loader’s handling of a class without module, then add or update a regression test in the unittest test suite. Done means the loader no longer crashes and the regression case passes.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
testing-qa
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.