Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PEP 604 Syntax Fails on Imported Types with Automock Imports #11211

Open
intermezzio opened this issue Feb 27, 2023 · 1 comment
Open

PEP 604 Syntax Fails on Imported Types with Automock Imports #11211

intermezzio opened this issue Feb 27, 2023 · 1 comment

Comments

@intermezzio
Copy link

Describe the bug

Sphinx raises an error when an imported type is joined with another type via the pipe operator in a type hint even though it is valid syntax for PEP 604.

How to Reproduce

import numpy as np

def func_1(inp: np.ndarray | None):
    pass # should work but doesn't

def func_2(inp: type(np.array([])) | None):
    pass # works but is cursed

def func_3(inp: np.ndarray):
    pass # works fine

def func_4(inp: list | None):
    pass # works fine

conf.py contains the following:

autodoc_mock_imports = ["numpy"]

Environment Information

Platform:              linux; (Linux-5.15.93-1-MANJARO-x86_64-with-glibc2.37)
Python version:        3.10.9 (main, Dec 19 2022, 17:35:49) [GCC 12.2.0])
Python implementation: CPython
Sphinx version:        6.1.3
Docutils version:      0.18.1
Jinja2 version:        3.1.2
Pygments version:      2.14.0

Sphinx extensions

["sphinx.ext.autodoc"]

Additional context

No response

@asaril
Copy link

asaril commented Aug 31, 2023

I think I just ran into the same issue when using an imported type from a mocked module in a PEP604 Union. (Similar versions, sphinx 6.1.3, python 3.10.12)

[edit] retried it with sphinx 7.2.5, same behavior (ext.autodoc.mock.py is mostly unchanged, so that was expected [/edit]

The mock factory creates a new type() in the mock module's getattr, and returns an instance of that.
The instance in itself is not a type, so it does not gain the | operator for types.

(also, calling & or | on the mock objects with any other value/object seems to not work).

If the mock is only used in a type-checking context, it could be worked around by either returning the type itself, or implementing a __or__(__value) method in _MockObject, that can return a typing.Union[self, __value].
Both of these could potentially break imports where it should have been a value/instance instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants