python / python/cpython

mock.patch cannot import an invalid-name module in >=3.11 due to importlib.import_module vs pkgutil.resolve_name differences when module has a dash in its filename

Open
#100,950 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug report

importlib.import_module() and pkgutil.resolve_name() are inconsistent with regards to which formats they accept. For example, if I have a module that contains a dash (-) in its filename (for example in a Django management command), importlib.import_module() is able to import the module just fine, while pkgutil.resolve_name() will raise an exception about an invalid format.

Minimal reproducer (all files are empty):

$ find . -name \*.py
./foobar/__init__.py
./foobar/foo-bar.py
$ python3 -c 'import importlib; importlib.import_module("foobar.foo-bar")'
$ python3 -c 'import pkgutil; pkgutil.resolve_name("foobar.foo-bar")'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python3.10/pkgutil.py", line 687, in resolve_name
    raise ValueError(f'invalid format: {name!r}')
ValueError: invalid format: 'foobar.foo-bar'

I would expect those to be consistent in the format they accept, i.e. accept and reject the same inputs.
My current actual problem is that unittest.mock.patch uses pkgutil.resolve_name() in Python 3.11 (but not in Python 3.10), what means that one cannot easily patch a function inside a Django management command module that contains a dash.

Your environment

Tested on Debian testing amd64 (x86_64) as of today, with both python 3.11.1 and 3.9.10.

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

Reproduce the example with foobar/foo-bar.py, then inspect pkgutil.py's resolve_name implementation and unittest.mock.patch where it is used. The change is done when names accepted by importlib.import_module are handled consistently by the patch path, with coverage for a module filename containing a dash.

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
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.