Skip to content

Commit

Permalink
[PyROOT] Actively wildcard imports from ROOT and its submodules
Browse files Browse the repository at this point in the history
With this commit, the user will get an `ImportError` when trying to do
`from ROOT import *` or for example `from ROOT.RooFit import *`.

Before this commit, such commands were succeeding but without actually
importing anything, which might me confusing to the user because the
expect that everything from ROOT gets imported.
  • Loading branch information
guitargeek committed Feb 5, 2024
1 parent e46c662 commit a107e37
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
21 changes: 20 additions & 1 deletion bindings/pyroot/pythonizations/python/ROOT/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,20 @@
else:
import __builtin__ as builtins


class _PoisonedDunderAll(object):
"""Dummy class used to trigger an ImportError on wildcard imports if the
__all__attribute of a module is an instance of this class.
"""

def __getitem__(self, _):
raise ImportError("Wildcard imports such as `from ROOT import *` are not possible in PyROOT")


# Prevent `from ROOT import *` by setting the __all__ attribute to something
# that will raise an ImportError on item retrieval.
__all__ = _PoisonedDunderAll()

_is_ipython = hasattr(builtins, "__IPYTHON__")

# Configure ROOT facade module
Expand Down Expand Up @@ -127,7 +141,12 @@ def is_package(self, fullname: str) -> bool:
return _lookup_root_module(fullname) is not None

def create_module(self, spec: ModuleSpec):
return _lookup_root_module(spec.name)
out = _lookup_root_module(spec.name)
# Prevent wildcard import for the submodule by setting the __all__
# attribute to something that will raise an ImportError on item
# retrieval.
out.__all__ = _PoisonedDunderAll()
return out

def exec_module(self, module):
pass
Expand Down
3 changes: 1 addition & 2 deletions bindings/pyroot/pythonizations/python/ROOT/_facade.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,8 @@ def __init__(self, module, is_ipython):
types.ModuleType.__init__(self, module.__name__)

self.module = module
# Importing all will be customised later
self.module.__all__ = []

self.__all__ = module.__all__
self.__name__ = module.__name__
self.__file__ = module.__file__
self.__cached__ = module.__cached__
Expand Down

0 comments on commit a107e37

Please sign in to comment.