Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

ENH: Make __module__ attribute coherent across API #27716

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

Merged
merged 4 commits into from
Nov 20, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
ENH: Refactor __module__ attribute across API
  • Loading branch information
mtsokol committed Nov 14, 2024
commit 88cbe514a17bcbe17f393f511a64869f17327167
2 changes: 2 additions & 0 deletions 2 numpy/__config__.py.in
Original file line number Diff line number Diff line change
Expand Up @@ -160,3 +160,5 @@ def show(mode=DisplayModes.stdout.value):
raise AttributeError(
f"Invalid `mode`, use one of: {', '.join([e.value for e in DisplayModes])}"
)

show.__module__ = "numpy"
3 changes: 3 additions & 0 deletions 3 numpy/_core/defchararray.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,7 @@ def less(x1, x2):
return compare_chararrays(x1, x2, '<', True)


@set_module("numpy.char")
def multiply(a, i):
"""
Return (a * i), that is string multiple concatenation,
Expand Down Expand Up @@ -313,6 +314,7 @@ def multiply(a, i):
raise ValueError("Can only multiply by integers")


@set_module("numpy.char")
def partition(a, sep):
"""
Partition each element in `a` around `sep`.
Expand Down Expand Up @@ -354,6 +356,7 @@ def partition(a, sep):
return np.stack(strings_partition(a, sep), axis=-1)


@set_module("numpy.char")
def rpartition(a, sep):
"""
Partition (split) each element around the right-most separator.
Expand Down
28 changes: 28 additions & 0 deletions 28 numpy/_core/multiarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,34 @@
promote_types.__module__ = 'numpy'
zeros.__module__ = 'numpy'
normalize_axis_index.__module__ = 'numpy.lib.array_utils'
add_docstring.__module__ = 'numpy.lib'
compare_chararrays.__module__ = 'numpy.char'


def _override___module__():
namespace_names = globals()
for ufunc_name in [
'absolute', 'arccos', 'arccosh', 'add', 'arcsin', 'arcsinh', 'arctan',
'arctan2', 'arctanh', 'bitwise_and', 'bitwise_count', 'invert',
'left_shift', 'bitwise_or', 'right_shift', 'bitwise_xor', 'cbrt',
'ceil', 'conjugate', 'copysign', 'cos', 'cosh', 'deg2rad', 'degrees',
'divide', 'divmod', 'equal', 'exp', 'exp2', 'expm1', 'fabs',
'float_power', 'floor', 'floor_divide', 'fmax', 'fmin', 'fmod',
'frexp', 'gcd', 'greater', 'greater_equal', 'heaviside', 'hypot',
'isfinite', 'isinf', 'isnan', 'isnat', 'lcm', 'ldexp', 'less',
'less_equal', 'log', 'log10', 'log1p', 'log2', 'logaddexp',
'logaddexp2', 'logical_and', 'logical_not', 'logical_or',
'logical_xor', 'matmul', 'maximum', 'minimum', 'remainder', 'modf',
'multiply', 'negative', 'nextafter', 'not_equal', 'positive', 'power',
'rad2deg', 'radians', 'reciprocal', 'rint', 'sign', 'signbit', 'sin',
'sinh', 'spacing', 'sqrt', 'square', 'subtract', 'tan', 'tanh',
'trunc', 'vecdot',
]:
ufunc = namespace_names[ufunc_name]
ufunc.__module__ = "numpy"


_override___module__()


# We can't verify dispatcher signatures because NumPy's C functions don't
Expand Down
40 changes: 40 additions & 0 deletions 40 numpy/_core/strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
add, multiply as _multiply_ufunc,
)
from numpy._core.multiarray import _vec_string
from numpy._core.overrides import set_module
from numpy._core.umath import (
isalpha,
isdigit,
Expand Down Expand Up @@ -48,6 +49,17 @@
)


def _override___module__():
for ufunc in [
isalnum, isalpha, isdecimal, isdigit, islower, isnumeric, isspace,
istitle, isupper, str_len,
]:
ufunc.__module__ = "numpy.strings"


_override___module__()


__all__ = [
# UFuncs
"equal", "not_equal", "less", "less_equal", "greater", "greater_equal",
Expand Down Expand Up @@ -116,6 +128,7 @@ def _clean_args(*args):
return newargs


@set_module("numpy.strings")
def multiply(a, i):
"""
Return (a * i), that is string multiple concatenation,
Expand Down Expand Up @@ -179,6 +192,7 @@ def multiply(a, i):
return _multiply_ufunc(a, i, out=out)


@set_module("numpy.strings")
def mod(a, values):
"""
Return (a % i), that is pre-Python 2.6 string formatting
Expand Down Expand Up @@ -215,6 +229,7 @@ def mod(a, values):
_vec_string(a, np.object_, '__mod__', (values,)), a)


@set_module("numpy.strings")
def find(a, sub, start=0, end=None):
"""
For each element, return the lowest index in the string where
Expand Down Expand Up @@ -252,6 +267,7 @@ def find(a, sub, start=0, end=None):
return _find_ufunc(a, sub, start, end)


@set_module("numpy.strings")
def rfind(a, sub, start=0, end=None):
"""
For each element, return the highest index in the string where
Expand Down Expand Up @@ -294,6 +310,7 @@ def rfind(a, sub, start=0, end=None):
return _rfind_ufunc(a, sub, start, end)


@set_module("numpy.strings")
def index(a, sub, start=0, end=None):
"""
Like `find`, but raises :exc:`ValueError` when the substring is not found.
Expand Down Expand Up @@ -327,6 +344,7 @@ def index(a, sub, start=0, end=None):
return _index_ufunc(a, sub, start, end)


@set_module("numpy.strings")
def rindex(a, sub, start=0, end=None):
"""
Like `rfind`, but raises :exc:`ValueError` when the substring `sub` is
Expand Down Expand Up @@ -360,6 +378,7 @@ def rindex(a, sub, start=0, end=None):
return _rindex_ufunc(a, sub, start, end)


@set_module("numpy.strings")
def count(a, sub, start=0, end=None):
"""
Returns an array with the number of non-overlapping occurrences of
Expand Down Expand Up @@ -404,6 +423,7 @@ def count(a, sub, start=0, end=None):
return _count_ufunc(a, sub, start, end)


@set_module("numpy.strings")
def startswith(a, prefix, start=0, end=None):
"""
Returns a boolean array which is `True` where the string element
Expand Down Expand Up @@ -444,6 +464,7 @@ def startswith(a, prefix, start=0, end=None):
return _startswith_ufunc(a, prefix, start, end)


@set_module("numpy.strings")
def endswith(a, suffix, start=0, end=None):
"""
Returns a boolean array which is `True` where the string element
Expand Down Expand Up @@ -484,6 +505,7 @@ def endswith(a, suffix, start=0, end=None):
return _endswith_ufunc(a, suffix, start, end)


@set_module("numpy.strings")
def decode(a, encoding=None, errors=None):
r"""
Calls :meth:`bytes.decode` element-wise.
Expand Down Expand Up @@ -531,6 +553,7 @@ def decode(a, encoding=None, errors=None):
np.str_(''))


@set_module("numpy.strings")
def encode(a, encoding=None, errors=None):
"""
Calls :meth:`str.encode` element-wise.
Expand Down Expand Up @@ -575,6 +598,7 @@ def encode(a, encoding=None, errors=None):
np.bytes_(b''))


@set_module("numpy.strings")
def expandtabs(a, tabsize=8):
"""
Return a copy of each string element where all tab characters are
Expand Down Expand Up @@ -626,6 +650,7 @@ def expandtabs(a, tabsize=8):
return _expandtabs(a, tabsize, out=out)


@set_module("numpy.strings")
def center(a, width, fillchar=' '):
"""
Return a copy of `a` with its elements centered in a string of
Expand Down Expand Up @@ -693,6 +718,7 @@ def center(a, width, fillchar=' '):
return _center(a, width, fillchar, out=out)


@set_module("numpy.strings")
def ljust(a, width, fillchar=' '):
"""
Return an array with the elements of `a` left-justified in a
Expand Down Expand Up @@ -756,6 +782,7 @@ def ljust(a, width, fillchar=' '):
return _ljust(a, width, fillchar, out=out)


@set_module("numpy.strings")
def rjust(a, width, fillchar=' '):
"""
Return an array with the elements of `a` right-justified in a
Expand Down Expand Up @@ -819,6 +846,7 @@ def rjust(a, width, fillchar=' '):
return _rjust(a, width, fillchar, out=out)


@set_module("numpy.strings")
def zfill(a, width):
"""
Return the numeric string left-filled with zeros. A leading
Expand Down Expand Up @@ -865,6 +893,7 @@ def zfill(a, width):
return _zfill(a, width, out=out)


@set_module("numpy.strings")
def lstrip(a, chars=None):
"""
For each element in `a`, return a copy with the leading characters
Expand Down Expand Up @@ -912,6 +941,7 @@ def lstrip(a, chars=None):
return _lstrip_chars(a, chars)


@set_module("numpy.strings")
def rstrip(a, chars=None):
"""
For each element in `a`, return a copy with the trailing characters
Expand Down Expand Up @@ -954,6 +984,7 @@ def rstrip(a, chars=None):
return _rstrip_chars(a, chars)


@set_module("numpy.strings")
def strip(a, chars=None):
"""
For each element in `a`, return a copy with the leading and
Expand Down Expand Up @@ -1000,6 +1031,7 @@ def strip(a, chars=None):
return _strip_chars(a, chars)


@set_module("numpy.strings")
def upper(a):
"""
Return an array with the elements converted to uppercase.
Expand Down Expand Up @@ -1036,6 +1068,7 @@ def upper(a):
return _vec_string(a_arr, a_arr.dtype, 'upper')


@set_module("numpy.strings")
def lower(a):
"""
Return an array with the elements converted to lowercase.
Expand Down Expand Up @@ -1072,6 +1105,7 @@ def lower(a):
return _vec_string(a_arr, a_arr.dtype, 'lower')


@set_module("numpy.strings")
def swapcase(a):
"""
Return element-wise a copy of the string with
Expand Down Expand Up @@ -1111,6 +1145,7 @@ def swapcase(a):
return _vec_string(a_arr, a_arr.dtype, 'swapcase')


@set_module("numpy.strings")
def capitalize(a):
"""
Return a copy of ``a`` with only the first character of each element
Expand Down Expand Up @@ -1150,6 +1185,7 @@ def capitalize(a):
return _vec_string(a_arr, a_arr.dtype, 'capitalize')


@set_module("numpy.strings")
def title(a):
"""
Return element-wise title cased version of string or unicode.
Expand Down Expand Up @@ -1191,6 +1227,7 @@ def title(a):
return _vec_string(a_arr, a_arr.dtype, 'title')


@set_module("numpy.strings")
def replace(a, old, new, count=-1):
"""
For each element in ``a``, return a copy of the string with
Expand Down Expand Up @@ -1416,6 +1453,7 @@ def _splitlines(a, keepends=None):
a, np.object_, 'splitlines', _clean_args(keepends))


@set_module("numpy.strings")
def partition(a, sep):
"""
Partition each element in ``a`` around ``sep``.
Expand Down Expand Up @@ -1483,6 +1521,7 @@ def partition(a, sep):
return _partition_index(a, sep, pos, out=(out["f0"], out["f1"], out["f2"]))


@set_module("numpy.strings")
def rpartition(a, sep):
"""
Partition (split) each element around the right-most separator.
Expand Down Expand Up @@ -1551,6 +1590,7 @@ def rpartition(a, sep):
a, sep, pos, out=(out["f0"], out["f1"], out["f2"]))


@set_module("numpy.strings")
def translate(a, table, deletechars=None):
"""
For each element in `a`, return a copy of the string where all
Expand Down
4 changes: 2 additions & 2 deletions 4 numpy/_core/tests/test_umath.py
Original file line number Diff line number Diff line change
Expand Up @@ -4026,7 +4026,7 @@ def test_ufunc_docstring(self):

del np.add.__doc__
assert np.add.__doc__ == original_doc
assert np.add.__dict__ == {}
assert np.add.__dict__ == {"__module__": "numpy"}

np.add.__dict__["other"] = 1
np.add.__dict__["__doc__"] = new_doc
Expand All @@ -4035,7 +4035,7 @@ def test_ufunc_docstring(self):
del np.add.__dict__["__doc__"]
assert np.add.__doc__ == original_doc
del np.add.__dict__["other"]
assert np.add.__dict__ == {}
assert np.add.__dict__ == {"__module__": "numpy"}


class TestChoose:
Expand Down
1 change: 1 addition & 0 deletions 1 numpy/_pytesttester.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ class PytestTester:
"""
def __init__(self, module_name):
self.module_name = module_name
self.__module__ = module_name

def __call__(self, label='fast', verbose=1, extra_argv=None,
doctests=False, coverage=False, durations=-1, tests=None):
Expand Down
Loading
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.