GeezerVison is showing github.com — DOC: any class decorated with `@set_module` does not show its source on automatically generated documentation · Issue #28629 · numpy/numpy
DOC: any class decorated with @set_module does not show its source on automatically generated documentation #28629DescriptionDescribe the issue:
Any class decorated using the the decorator set_module('to_this_module'), defined on numpy/_utils/__init__.py, is pointing the location of it's source code in the wrong place in externally generated docs. This error affects the automatically generated link appearing as a [source], in the function header in the documentation web site, and also in the File: attribute appearing in the footer of the helper shown by the IPython magic helper operator ?.
As an example, consider the poly1d class definition, which is located on file numpy/lib/_polynomial_impl.py, an screenshot of the documentation is shown below indicating that the code is located at `numpy/init.py

The same error appears while calling the ? np.poly1d helper on IPython, which results in
Init signature: np.poly1d(c_or_r, r=False, variable=None)
Docstring: ... (omited)
File: ~/mycode/numpy-aureliobarbosa/numpy-dev/lib/python3.12/site-packages/numpy/__init__.py
Type: type
Subclasses:
This error currently affects at least 25 classes, which can be tracked in the repository with the regex @set_module\(['"].*?['"]\)\nclass (I used VSCode for that). The full list of affected classes will complement this message. This problem doen't affect functions decorated with set_module as will become clear in the following
After some investigation I found that external tools (numpydoc ?, IPython) automatically searching for where the source code of a certain object is located rely on the stdlib function inpect.getfile(object) (or another function on the module inspect which will call getfile) to recover the actual location of the code in the directory tree. This function is simple and it's code can be found here, and in the case of classes, it end up calling the following code:
module = sys.modules.get(object.__module__)
if getattr(module, '__file__', None):
return module.__file__
which will return the __init__.py file of the module passed using @set_module('module'), since this decorator dynamically changes the the property __module__ of a class or a function. Using @set_module('module') to decorate functions doesn't harm documentation because when calling inspect.getfile(object), when object is a function, returns object.__code__.co_filename, which wasn't affected by the set_module decorator.
My original intention was to try to fix the documentation but it turned it out that the problem is originating in the decorator @set_module which, in my opinion, is breaking a contract that is commonly expected by other tools operating on a property of classes, as it also affects the behavior of IPython.
It should be possible to fix the online documentation (maybe changing numpydoc?) but the problem would continue to exist in any tool which automatically try to locate the source code of those classes in a standard way. In order to fix this documentation/code issue a decision a decision should be made concerning the usage of the decorator @set_module.
Although using numpy for some time, I am still new on its codebase, if someone can give me a hint on the reasons for using @set_module it would help to implement a fix. Anyway, hope the current investigation helps when searching for a solution to this issue.
Regards
Reproduce the code example:
import sys
import numpy as np
object = np.poly1d
module = sys.modules.get(object.__module__)
print(module.__file__)
# should be expecting '<codebase>/numpy/lib/_polynomial_impl.py'
Error message:
Python and NumPy Versions:
Python: 3.12.8
NumPy: 2.2.4
IPython: 9.0.4
Runtime Environment:
No response
Context for the issue:
No response Activitychanged the title [-]BUG: any class decorated with @set_module does not show its source on automatically generated DOC[/-] [+]BUG: any class decorated with `@set_module does not show its source on automatically generated documentation[/+] on Apr 2, 2025changed the title [-]BUG: any class decorated with `@set_module does not show its source on automatically generated documentation[/-] [+]BUG: any class decorated with `@set_module` does not show its source on automatically generated documentation[/+] on Apr 2, 2025aureliobarbosa commented on Apr 2, 2025 ContributorAuthor More actions Affected classes:
numpy/_core/_ufunc_config.py:
362
363: @set_module('numpy')
364: class errstate:
365 """
numpy/_core/defchararray.py:
402
403: @set_module("numpy.char")
404: class chararray(ndarray):
405 """
numpy/_core/getlimits.py:
383
384: @set_module('numpy')
385: class finfo:
386 """
638
639: @set_module('numpy')
640: class iinfo:
641 """
numpy/_core/memmap.py:
20
21: @set_module('numpy')
22: class memmap(ndarray):
23 """Create a memory-map to an array stored in a *binary* file on disk.
numpy/_core/records.py:
55
56: @set_module('numpy.rec')
57: class format_parser:
58 """
281
282: @set_module("numpy.rec")
283: class recarray(ndarray):
284 """Construct an ndarray that allows field access using attributes.
numpy/_typing/_nbit_base.py:
6 @final # Disallow the creation of arbitrary `NBitBase` subclasses
7: @set_module("numpy.typing")
8: class NBitBase:
9 """
67 @final
68: @set_module("numpy._typing")
69: class _128Bit(_256Bit): # type: ignore[misc]
70 pass
72 @final
73: @set_module("numpy._typing")
74: class _96Bit(_128Bit): # type: ignore[misc]
75 pass
77 @final
78: @set_module("numpy._typing")
79: class _80Bit(_96Bit): # type: ignore[misc]
80 pass
82 @final
83: @set_module("numpy._typing")
84: class _64Bit(_80Bit): # type: ignore[misc]
85 pass
87 @final
88: @set_module("numpy._typing")
89: class _32Bit(_64Bit): # type: ignore[misc]
90 pass
92 @final
93: @set_module("numpy._typing")
94: class _16Bit(_32Bit): # type: ignore[misc]
95 pass
97 @final
98: @set_module("numpy._typing")
99: class _8Bit(_16Bit): # type: ignore[misc]
100 pass
numpy/lib/_datasource.py:
195
196: @set_module('numpy.lib.npyio')
197: class DataSource:
198 """
numpy/lib/_function_base_impl.py:
2271
2272: @set_module('numpy')
2273: class vectorize:
2274 """
numpy/lib/_index_tricks_impl.py:
592
593: @set_module('numpy')
594: class ndenumerate:
595 """
642
643: @set_module('numpy')
644: class ndindex:
645 """
numpy/lib/_npyio_impl.py:
106
107: @set_module('numpy.lib.npyio')
108: class NpzFile(Mapping):
109 """
numpy/lib/_polynomial_impl.py:
1086
1087: @set_module('numpy')
1088: class poly1d:
1089 """
numpy/lib/_user_array_impl.py:
18
19: @set_module("numpy.lib.user_array")
20: class container:
21 """
numpy/linalg/_linalg.py:
72
73: @set_module('numpy.linalg')
74: class LinAlgError(ValueError):
75 """
numpy/ma/core.py:
2764
2765: @set_module("numpy.ma")
2766: class MaskedArray(ndarray):
2767 """
numpy/matrixlib/defmatrix.py:
71
72: @set_module('numpy')
73: class matrix(N.ndarray):
74 """seberg commented on Apr 2, 2025 The set_module is there so that the module is what we consider the place where the public API lives (and not where it's defined). For one, that is actually (slightly) relevant for pickling, and also some downstream packages have very strong assumptions about this (even though I would agree that almost no-one worries about this, NumPy is the huge outlier here due to dispatching).
I would be happy if we can fix things so that sphinx manages to find it (whatever that means exactly!), but I am not sure what the solution for this could be.
(Sphinx isn't the only tool that gets confused by this.) aureliobarbosa commented on Apr 2, 2025 ContributorAuthor More actions Should it be possible to indicate a downstream package using __module__ from a numpy function or module and expecting it to be as set by using @set_module? As far as the examples shows in the docs states, if functions and classes can be found always in the same route, even after reorganizing the source tree and doing imports on init.py (as the numpy modules do), regular calls to numpy modules will work even without set_module.
Sad another way, are there conditions in which @set_module is only way for an extension module (maybe written in another language) to locate a function or class?
Besides that, I am not used with Sphinx, but shouldn't it be possible to (at least) fix numpy's own documentation by changing some template on numpy (or numpydoc) side?
I am asking because I am interested in trying to fix it. seberg commented on Apr 3, 2025 There are reasons, downstream wants to be able to rely on func.__module__ and pickling is more stable. You would have to argue that those outweigh the bad [source] button.
And I am not convinced they do and don't feel like diving into it more, TBH. There were some "bug reports" not too long ago, because not all functions used set_module.
The ideal solution is to make is to teach sphinx to find the correct source position, or somehow make it easier to find in general. I believe obj.__code__ often holds the information, but not sure about always (and it may be CPython specific). mhvk commented on Apr 3, 2025 Part of the reason for introducting set_module was (I think) that the definitions of functions and classes were almost all changed in the transition to numpy 2.0 (to "private" modules). Arguably, that transition has happened, so it is less obviously needed any more.
I do think sticking to standards is important, and that breaking sphinx by not doing so is quite bad -- it is super useful to be able to just go to the source right from the documentation (and similarly for ipython's ? to point to the right place). So, I think it would be really good to fix this. The fact that this might involve having to change the standard library does suggest the problem is numpy's "hack" of changing __module__... (unless there is a simple and robust fix for the standard library).
Also, at least for pickle a relatively straightforward fix may be possible: one just needs to intercept the writing of where the class is defined, which could be done fairly straightforwardly by overriding the pickle state and inserting the relevant numpy module. Indeed, set_module itself could probably do that... (maybe using a mixin class). seberg commented on Apr 3, 2025 Sorry for not going into more depth. The 2.0 thing just added it to a few functions because pytorch ended up relying on this, but it wasn't added for that.
I suspect this was added for __array_function__, to normalize what the "public API" is. I would have suspected that for dispatching it allows you to use __array_function__ without importing NumPy (although I guess you could maybe do that import inside __array_function__. ngoldbaum commented on Apr 3, 2025 I also have a preference for fixing this in sphinx or in our sphinx config rather than making any functional changes to NumPy to work around sphinx limitations. seberg commented on Apr 3, 2025
and similarly for ipython's ? to point to the right place)
This one manages, I think, because it uses __code__.
Anyway, I am not opposed to saying that @set_module may have done more harm than good. But I am not quite convinced that changing it there is worthwhile right now.
Just for sphinx, it might even work to just disable it during the sphinx build, although I suspect it's better to teach it to try __code__ first. mhvk commented on Apr 3, 2025
I also have a preference for fixing this in sphinx or in our sphinx config rather than making any functional changes to NumPy to work around sphinx limitations.
Sure, if that works. Though I think it is really numpy that is doing strange things here -- resetting dunder methods should come with thinking about how other code relies on those and certainly not blaming code for interpreting them as intended. Indeed, the python data model states that __module__ is "The name of the module the function was defined in, or None if unavailable." That does not seem ambiguous. It is not the module the function should be imported from, but the one it is defined in.
That said, set_module solved a problem, so whatever we do should try not to reintroduce that. But really it would be good to get rid of this. seberg commented on Apr 3, 2025 For references: #12271, I agree NumPy is the odd one even if this has some advantages (i.e. allowing internal refactor without anyone caring), it has its downsides.
Those issues are actually very murky about the reasons (besides that you have to fix __module__, I am not sure it explains that it must be the public one).
The name of the module the function was defined in
Hehe, yeah, that is the obvious meaning, but not sure it doesn't get morphed quickly if you have code that assumes the opposite (i.e. pytorch): #27716 (ok, that is "originates").
I would be curious about solutions that allow our way, because I do think it has some clear advantages as well. But I suppose that might even a something that Python would have to learn better (maybe as inspect.find_definition_file/module()). changed the title [-]BUG: any class decorated with `@set_module` does not show its source on automatically generated documentation[/-] [+]DOC: any class decorated with `@set_module` does not show its source on automatically generated documentation[/+] on Apr 4, 2025aureliobarbosa commented on Apr 4, 2025 ContributorAuthor More actions It should be interesting to note that as of python 3.13 the data model mentions the possibility of overriding the __module__ attribute, since the class attribute type.__firstlineno__ considers that "Setting the __module__ attribute removes the __firstlineno__ item from the type’s dictionary." (ref). Thus the issue about overriding the module location got the attention of at least one python core developer.
I'm currently working on a fix which may resolve numpy' s documentation issue, but wouldn't change the status of other tools. It consists in changing set_module so that it annotates the original __module__ on decorated objects, while also changing the sphinx configuration file on numpy's side: the external source links are resolved by the sphinx plugin linkcode through the function linkcode_resolve on doc/source/conf.py.
A draft PR was submitted with this findings and as soon as possible I will try to implement the above mentioned idea. If there are any restriction toward proceeding on this direction, just let me now. seberg commented on Apr 4, 2025
It should be interesting to note that as of python 3.13 the data model mentions the possibility of overriding the module attribute, since the class attribute type.firstlineno
Too bad this wasn't __code_location__ that include the file name, that would solve this dilemma for us. mhvk commented on Apr 4, 2025 Indeed, that seems a bit of a wasted opportunity. It also means sphinx by default my soon start using __firstlineno__, so that fact that is disappears on setting __module__ perhaps argues again to not replace __module__ in the first place.
@aureliobarbosa - given this, while your plan may work, I do worry it is just stacking hack upon hack -- in general, sphinx's conf.py files are too full of black magic already and I worry about making that even more fragile. In that respect, it might be nicer to just try to solve the original problems without changing __module__ in the first place (e.g., with overriding what pickle stores -- see above). This may need some interaction with pytorch to do it in a way that they can adjust to (haven't yet looked at what their problem really was, though). aureliobarbosa commented on Apr 4, 2025 ContributorAuthor More actions I agree with @mhvk in that changing sphinx conf.py would be doubling on the hacking side.
Nevertheless, I will keep the PR as draft and update here if it works, later. Not using set_module would be ideal because in this way documentation would work everywhere, but as noted, it may demand more investigations and coordination. seberg commented on Apr 4, 2025 @aureliobarbosa one note I have is that NumPy has practically no classes at all in it's public API (at least no interesting ones that are also defined in Python).
So it might make sense to focus a bit on functions, for which I think making sure that __code__ is propagated may be the path to fixing it within sphinx. aureliobarbosa commented on Apr 8, 2025 ContributorAuthor More actions @seberg and @mhvk
I just submitted the PR with a fix, specific for the documentation issue.
Edit MHvK: gh-28645
MetadataMetadataDevelopmentNo branches or pull requestsIssue actions
|