Skip to content

Importing IPython confuses mypy about package '__main__.py' #19500

@dmcooke

Description

@dmcooke

I have a package with a __main__.py in it. I discovered that if

  • you run mypy in the package directory on the __main__.py
  • and at some point your code (or another package's code) imports IPython
  • then I get the following error:
__main__.py: error: Source file found twice under different module names: "foopy.__main__" and "__main__"
__main__.py: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#mapping-file-paths-to-modules for more info
__main__.py: note: Common resolutions include: a) adding `__init__.py` somewhere, b) using `--explicit-package-bases` or adjusting MYPYPATH
Found 1 error in 1 file (errors prevented further checking)

I should note that adding --explicit-package-bases, as suggested, does prevent this error. However, the specific set of circumstances required to trigger this seems problematic, especially as there is a top-level __init__.py.

Exact minimal steps to reproduce:

$ mkdir foo; cd foo
$ mkdir foopy

# Create the source: an empty __init__.py, and a __main__.py
# that only imports IPython.

$ touch foopy/__init__.py
$ echo 'import IPython' > foopy/__main__.py

# Running mypy in the project directory works

$ mypy foopy/__main__.py
Success: no issues found in 1 source file

# But not when in the foopy package directory

$ cd foopy
$ mypy __main__.py
__main__.py: error: Source file found twice under different module names: "foopy.__main__" and "__main__"
<...rest as above...>

The error occurs with both my system-installed mypy 1.15.0 and ipython 8.35.0 (Debian unstable), and with the current versions mypy 1.17.0 and ipython 9.4.0 installed in a new venv with pip. The Python version is 3.13.5.

Some observations:

  • You have to run mypy in the package directory (this is what the flycheck package
    for emacs does, which is how I discovered/got bothered by it).
  • So far, only IPython appears to trigger this.
    • importing IPython's dependencies instead doesn't trigger it
    • Other packages with a __main__.py that I've tried can be imported without issue

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions