Skip to content

Improve the process of obtaining known_symbols for use in code generation #354

@junkmd

Description

@junkmd

target part

def _get_known_symbols():
known_symbols = {}
for name in ("comtypes.persist",
"comtypes.typeinfo",
"comtypes.automation",
"comtypes._others",
"comtypes",
"ctypes.wintypes",
"ctypes"):
try:
mod = __import__(name)
except ImportError:
if name == "comtypes._others":
continue
raise
for submodule in name.split(".")[1:]:
mod = getattr(mod, submodule)
for name in mod.__dict__:
known_symbols[name] = mod.__name__
return known_symbols

from builtin __import__ to importlib.import_module

The documentation said

Programmatic importing of modules should use import_module() instead of this function.

And,

The most important difference between these two functions is that import_module() returns the specified package or module (e.g. pkg.mod), while __import__() returns the top-level package or module (e.g. pkg).

Therefore, below part will be no longer.

for submodule in name.split(".")[1:]:
mod = getattr(mod, submodule)

Explicitly specify symbols to be imported from comtypes.foo

for name in mod.__dict__:
known_symbols[name] = mod.__name__

Currently, all symbols in comtypes.foo are known_symbols.
This could lead to accidental import symbols that are not COM objects or c-ffi.

There will be fewer accidents if the dictionary is statically defined rather than dynamically created depending on the namespace of the module.

No more try to import comtypes._others

Since comtypes._others is a non-existent module, importing will always fail.
There should be no significance of the branching within except.
So, the following code should be replaced with a single line of mod = importlib.import_module(name) without any problem.

try:
mod = __import__(name)
except ImportError:
if name == "comtypes._others":
continue
raise

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions