Skip to content

Commit

Permalink
Fix importing newly-created modules on Python 3
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
François-Xavier Thomas committed Oct 23, 2018
1 parent 1d3d38b commit 4ea51e1
Showing 1 changed file with 7 additions and 0 deletions.
7 changes: 7 additions & 0 deletions comtypes/client/_generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import sys
import comtypes.client
import comtypes.tools.codegenerator
import importlib

import logging
logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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

Expand Down

0 comments on commit 4ea51e1

Please sign in to comment.