Skip to content

Fix ModuleNotFoundError for __main__ when run from entry points#1072

Open
worksbyfriday wants to merge 2 commits intoagronholm:masterfrom
worksbyfriday:fix-entrypoint-main-setup
Open

Fix ModuleNotFoundError for __main__ when run from entry points#1072
worksbyfriday wants to merge 2 commits intoagronholm:masterfrom
worksbyfriday:fix-entrypoint-main-setup

Conversation

@worksbyfriday
Copy link
Copy Markdown

Summary

Fixes ModuleNotFoundError: No module named '__main__' when to_process.run_sync() is called from a package entry point (console_scripts).

Fixes #1027

Root cause

When __main__.__file__ points to an entry point script without a .py extension, spec_from_file_location returns None. The worker's init code deletes sys.modules["__main__"] (line 233) but never restores it, because the spec guard at line 239 skips module loading. Libraries like dill that subsequently try import __main__ get ModuleNotFoundError.

Fix

After the init block, if "__main__" is no longer in sys.modules, create a placeholder types.ModuleType("__main__"). This matches multiprocessing's approach for handling non-importable main modules.

Test plan

  • New test test_entrypoint_main_module: sets __main__.__file__ to a real file without .py extension, verifies worker can still access __main__ via sys.modules
  • All 30 existing test_to_process.py tests pass (10 skipped for uvloop)

worksbyfriday and others added 2 commits February 17, 2026 21:56
When to_process.run_sync() is called from a package entry point
(console_scripts), the worker's __main__.__file__ points to a script
without a .py extension. spec_from_file_location returns None for
such paths, leaving __main__ deleted from sys.modules and causing
ModuleNotFoundError when libraries like dill try to import it.

Create a placeholder __main__ module when spec_from_file_location
fails to resolve the entry point path, matching multiprocessing's
approach.

Fixes agronholm#1027
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.

to_process.run_sync fails to set up __main__ in worker process when run from an entry point

1 participant