From 07cc8cb961629c9fd883564ef57808b232584e8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois-Xavier=20Thomas?= Date: Tue, 23 Oct 2018 10:26:27 +0200 Subject: [PATCH] Fix importing newly-created modules on Python 3 Python 3's import mechanism caches the contents of a directory containing modules (such as comtypes.gen) and relies on the "modified time" (mtime) attribute to determine if it needs to reload that directory. In Windows, the mtime is sometimes not updated very often when creating modules in quick succession, which means that the mtime stays identical, which then appears in comtype's case as random module import failures when using a new COM object for the first time. --- comtypes/client/_generate.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/comtypes/client/_generate.py b/comtypes/client/_generate.py index 1d0a350c..bb9e2cda 100644 --- a/comtypes/client/_generate.py +++ b/comtypes/client/_generate.py @@ -3,6 +3,7 @@ import sys import comtypes.client import comtypes.tools.codegenerator +import importlib import logging logger = logging.getLogger(__name__) @@ -143,6 +144,9 @@ def GetModule(tlib): ofi = open(os.path.join(comtypes.client.gen_dir, modulename + ".py"), "w") ofi.write(code) ofi.close() + # clear the import cache to make sure Python sees newly created modules + if hasattr(importlib, "invalidate_caches"): + importlib.invalidate_caches() return _my_import("comtypes.gen." + modulename) def _CreateWrapper(tlib, pathname=None): @@ -181,6 +185,9 @@ def _CreateWrapper(tlib, pathname=None): setattr(comtypes.gen, modname, mod) else: ofi.close() + # clear the import cache to make sure Python sees newly created modules + if hasattr(importlib, "invalidate_caches"): + importlib.invalidate_caches() mod = _my_import(fullname) return mod