Skip to content

Commit 988f6a4

Browse files
committed
optimize _add_imports_to_all
1 parent 1ae6bda commit 988f6a4

File tree

1 file changed

+24
-16
lines changed

1 file changed

+24
-16
lines changed
Lines changed: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,31 @@
1-
import inspect
1+
import sys
2+
import types
23

34

45
def _add_imports_to_all(include_modules: bool | list[str] = False, exclude: list[str] | None = None):
56
"""Add all global variables to __all__"""
67
if not isinstance(include_modules, (bool, list)):
78
raise ValueError("include_modules must be a boolean or a list of strings")
89

9-
exclude = exclude or []
10-
calling_module = inspect.stack()[1]
11-
local_stack = calling_module[0]
12-
global_vars = local_stack.f_globals
13-
all_vars = global_vars["__all__"] if "__all__" in global_vars else []
14-
included_vars = []
15-
for var_name in set(global_vars.keys()):
16-
if inspect.ismodule(global_vars[var_name]):
17-
if include_modules is True and var_name not in exclude and not var_name.startswith("_"):
18-
included_vars.append(var_name)
19-
elif isinstance(include_modules, list) and var_name in include_modules:
20-
included_vars.append(var_name)
21-
elif var_name not in exclude and not var_name.startswith("_"):
22-
included_vars.append(var_name)
23-
global_vars["__all__"] = sorted(list(set(all_vars).union(included_vars)))
10+
exclude_set = set(exclude or [])
11+
contains = exclude_set.__contains__
12+
mod_type = types.ModuleType
13+
frame = sys._getframe(1)
14+
g: dict = frame.f_globals
15+
existing = set(g.get("__all__", []))
16+
17+
to_add = []
18+
include_list = include_modules if isinstance(include_modules, list) else ()
19+
inc_all = include_modules is True
20+
21+
for name, val in g.items():
22+
if name.startswith("_") or contains(name):
23+
continue
24+
25+
if isinstance(val, mod_type):
26+
if inc_all or name in include_list:
27+
to_add.append(name)
28+
else:
29+
to_add.append(name)
30+
31+
g["__all__"] = sorted(existing.union(to_add))

0 commit comments

Comments
 (0)