From 7ca83750a924722924b5e61a7173c987a10c10e0 Mon Sep 17 00:00:00 2001 From: Adraub Date: Fri, 31 Oct 2025 23:59:11 +0100 Subject: [PATCH 1/2] Fix RuntimeWarning: 'tf2onnx.convert' found in sys.modules after import of package 'tf2onnx', but prior to execution of 'tf2onnx.convert' Signed-off-by: Adraub --- tf2onnx/__init__.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tf2onnx/__init__.py b/tf2onnx/__init__.py index f1bdd6508..de92c1725 100644 --- a/tf2onnx/__init__.py +++ b/tf2onnx/__init__.py @@ -8,4 +8,3 @@ import onnx from .version import git_version, version as __version__ from . import verbose_logging as logging -from tf2onnx import tfonnx, utils, graph, graph_builder, graph_matcher, shape_inference, schemas, convert # pylint: disable=wrong-import-order From cdcadb8a679047e744c6515bfdd3228ee9f53234 Mon Sep 17 00:00:00 2001 From: Adraub Date: Mon, 3 Nov 2025 22:15:35 +0100 Subject: [PATCH 2/2] Add lazy loading for submodules in __init__.py Fixes some UT missing some submodules after removing heavy import Signed-off-by: Adraub --- tf2onnx/__init__.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/tf2onnx/__init__.py b/tf2onnx/__init__.py index de92c1725..9e1e4999f 100644 --- a/tf2onnx/__init__.py +++ b/tf2onnx/__init__.py @@ -5,6 +5,25 @@ __all__ = ["utils", "graph_matcher", "graph", "graph_builder", "tfonnx", "shape_inference", "schemas", "tf_utils", "tf_loader", "convert"] +import importlib import onnx from .version import git_version, version as __version__ from . import verbose_logging as logging + +# NOTE: Importing heavily submodules here leads to a RuntimeWarning +# when launching "python -m tf2onnx.convert": +# "'tf2onnx.convert' found in sys.modules after import of package 'tf2onnx', +# but prior to execution of 'tf2onnx.convert'; this may result in unpredictable behaviour" +# To prevent that, lazily import submodules on attribute access using PEP 562. + +def __getattr__(name): + """Lazily import submodules listed in __all__ on attribute access.""" + if name in __all__: + module = importlib.import_module(f"tf2onnx.{name}") + globals()[name] = module + return module + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + +def __dir__(): + """Expose package attributes and available submodules for tab-completion.""" + return sorted(list(globals().keys()) + __all__)