From d274b92f1a21b1c7e6813d2a8f2032f5bf055aff 2023-05-04 08:49:02 From: Matthias Bussonnier Date: 2023-05-04 08:49:02 Subject: [PATCH] Backport PR #14029 on branch 8.12.x (Allow safe access to the `__getattribute__` method of modules) (#14065) Backport PR #14029: Allow safe access to the `__getattribute__` method of modules --- diff --git a/IPython/core/guarded_eval.py b/IPython/core/guarded_eval.py index 3c95213..1eca14d 100644 --- a/IPython/core/guarded_eval.py +++ b/IPython/core/guarded_eval.py @@ -637,6 +637,7 @@ set_non_mutating_methods = set(dir(set)) & set(dir(frozenset)) dict_keys: Type[collections.abc.KeysView] = type({}.keys()) method_descriptor: Any = type(list.copy) +module = type(builtins) NUMERICS = {int, float, complex} @@ -686,6 +687,7 @@ BUILTIN_GETATTR: Set[MayHaveGetattr] = { *NUMERICS, dict_keys, method_descriptor, + module, } diff --git a/IPython/core/tests/test_guarded_eval.py b/IPython/core/tests/test_guarded_eval.py index 905cf3a..6fb321a 100644 --- a/IPython/core/tests/test_guarded_eval.py +++ b/IPython/core/tests/test_guarded_eval.py @@ -568,3 +568,15 @@ def test_assumption_named_tuples_share_getitem(): pass assert A.__getitem__ == B.__getitem__ + + +@dec.skip_without("numpy") +def test_module_access(): + import numpy + + context = limited(numpy=numpy) + assert guarded_eval("numpy.linalg.norm", context) == numpy.linalg.norm + + context = minimal(numpy=numpy) + with pytest.raises(GuardRejection): + guarded_eval("np.linalg.norm", context)