From 58737b71d09f6c0a035d5c4cb3ec49b408cbfea9 Mon Sep 17 00:00:00 2001 From: "A. Unique TensorFlower" Date: Fri, 27 Nov 2026 07:32:29 -0800 Subject: [PATCH] Avoid inspect.stack() in tensorflow_graphics.util.export_api. Calling `inspect.stack()[1]` at module import time in `get_functions_and_classes()` and `get_modules()` inspects every outer frame on the call stack and triggers `inspect.getmodule()` scans across all entries in `sys.modules` for uncached import frames. In large Python applications with deep import stacks and thousands of loaded modules, this makes importing a handful of `tensorflow_graphics` modules take several seconds. Read the immediate caller frame directly via `sys._getframe(2)` and resolve its module in O(1) from `sys.modules` when `module.__dict__ is frame.f_globals`, falling back to `inspect.getmodule(frame)` otherwise. PiperOrigin-RevId: 1031264643 --- tensorflow_graphics/util/export_api.py | 18 ++++++-- .../util/tests/export_api_test.py | 43 +++++++++++++++---- 2 files changed, 48 insertions(+), 13 deletions(-) diff --git a/tensorflow_graphics/util/export_api.py b/tensorflow_graphics/util/export_api.py index ebd24971b..a5ebe556f 100644 --- a/tensorflow_graphics/util/export_api.py +++ b/tensorflow_graphics/util/export_api.py @@ -18,18 +18,29 @@ from __future__ import print_function import inspect +import sys import six +def _get_caller_module(): + """Returns the module of the caller of the public export_api function.""" + # Avoid inspect.stack() (O(depth * len(sys.modules))) and inspect.getmodule() + # on uncached newly-imported modules, which scans sys.modules and realpath(). + frame = sys._getframe(2) # pylint: disable=protected-access + module = sys.modules.get(frame.f_globals.get("__name__", "")) + if getattr(module, "__dict__", None) is frame.f_globals: + return module + return inspect.getmodule(frame) + + def get_functions_and_classes(): """Extracts a list of public functions and classes for the API generation. Returns: A list of function and class names. """ - caller = inspect.stack()[1] - module = inspect.getmodule(caller[0]) + module = _get_caller_module() return [ obj_name for obj_name, obj in inspect.getmembers(module) if inspect.isfunction(obj) or @@ -43,8 +54,7 @@ def get_modules(): Returns: A list of module names. """ - caller = inspect.stack()[1] - module = inspect.getmodule(caller[0]) + module = _get_caller_module() return [ obj_name for obj_name, obj in inspect.getmembers(module) if inspect.ismodule(obj) and six.ensure_str(obj.__name__).rsplit(".", 1) diff --git a/tensorflow_graphics/util/tests/export_api_test.py b/tensorflow_graphics/util/tests/export_api_test.py index 7b1bf801e..c79880474 100644 --- a/tensorflow_graphics/util/tests/export_api_test.py +++ b/tensorflow_graphics/util/tests/export_api_test.py @@ -13,25 +13,50 @@ # limitations under the License. """Tests for export API functionalities.""" +import sys +import types + from tensorflow_graphics.util import export_api from tensorflow_graphics.util import test_case +def sample_public_function(): + """Sample public function for export_api testing.""" + + +class _SamplePrivateClass: + """Sample private class for export_api testing.""" + + class ExportAPITest(test_case.TestCase): def test_get_functions_and_classes(self): - """Tests that get_functions_and_classes does not raise an exception.""" - try: - export_api.get_functions_and_classes() - except Exception as e: # pylint: disable=broad-except - self.fail("Exception raised: %s" % str(e)) + """Tests that get_functions_and_classes returns public symbols.""" + exported = export_api.get_functions_and_classes() + self.assertIn("ExportAPITest", exported) + self.assertIn("sample_public_function", exported) + self.assertNotIn("_SamplePrivateClass", exported) def test_get_modules(self): - """Tests that get_modules does not raise an exception.""" + """Tests that get_modules returns public direct submodules.""" + self.assertEqual(export_api.get_modules(), []) + + pkg_name = "_tfg_export_api_test_pkg" + pkg = types.ModuleType(pkg_name) + pkg.__dict__["export_api"] = export_api + pkg.__dict__["child"] = types.ModuleType(pkg_name + ".child") + pkg.__dict__["_private"] = types.ModuleType(pkg_name + "._private") + pkg.__dict__["other"] = types.ModuleType("unrelated_pkg.other") + + def _call(): + return export_api.get_modules() + + sys.modules[pkg_name] = pkg try: - export_api.get_modules() - except Exception as e: # pylint: disable=broad-except - self.fail("Exception raised: %s" % str(e)) + call_in_pkg = types.FunctionType(_call.__code__, pkg.__dict__) + self.assertEqual(call_in_pkg(), ["child"]) + finally: + sys.modules.pop(pkg_name, None) if __name__ == "__main__":