Skip to content

scripts: fix crash when loading addon scripts that define a dataclass - #8293

Open
gaurav0107 wants to merge 2 commits into
mitmproxy:mainfrom
gaurav0107:fix/8279-can-t-use-dataclass-in-the-script
Open

gaurav0107 wants to merge 2 commits into
mitmproxy:mainfrom
gaurav0107:fix/8279-can-t-use-dataclass-in-the-script

Conversation

@gaurav0107

Copy link
Copy Markdown
Contributor

Description

Loading an addon script that defines a @dataclass currently crashes:

@dataclass
  File ".../dataclasses.py", line ..., in _process_class
    ... = sys.modules.get(cls.__module__).__dict__
AttributeError: 'NoneType' object has no attribute '__dict__'

The root cause is in mitmproxy.addons.script.load_script: it builds the
module with importlib.util.module_from_spec(spec) and then calls
loader.exec_module(m) without first registering the module in
sys.modules
. Python's import documentation recommends inserting the module
into sys.modules before executing it, because parts of the standard library
(dataclasses, pickling, typing.get_type_hints, ...) look the defining
module up in sys.modules by its __module__ name while the class body runs.
When the entry is missing the lookup returns None and the decorator raises.

This registers the module in sys.modules before execution and removes it
again if execution fails, so a failed load still leaves nothing behind. The
existing sys.modules.pop(fullname, None) at the top of load_script keeps
guaranteeing uniqueness across reloads.

Closes #8279

Checklist

  • I have updated tests where applicable.
  • I have added an entry to the CHANGELOG.

Summary

  • Register addon-script modules in sys.modules before exec_module, and
    unregister on failure.
  • Add a regression test (test_load_script_with_dataclass) and a
    dataclass.py addon fixture that fails to load without the fix.
  • Add a CHANGELOG entry.

@gaurav0107
gaurav0107 marked this pull request as ready for review June 27, 2026 17:54
gaurav0107 and others added 2 commits July 24, 2026 01:11
Register the script module in sys.modules before executing it, as
recommended by the importlib docs. dataclasses (and other standard
library machinery such as pickling and typing.get_type_hints) look the
defining module up in sys.modules by its __module__ name while the
module body runs; without the module being registered, a script that
defines a @DataClass fails to load. Remove the module again if execution
fails so a broken load leaves nothing registered.

Closes mitmproxy#8279
@gaurav0107
gaurav0107 force-pushed the fix/8279-can-t-use-dataclass-in-the-script branch from 24df0e0 to 305aad3 Compare July 23, 2026 19:42

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Can't use @dataclass in the script

1 participant