Skip to content

Commit

Permalink
Merge pull request #1695 from itamarst/1694-import_hook-order
Browse files Browse the repository at this point in the history
Packages are now rebuilt every time they are imported, instead of only ever once per virtualenv
  • Loading branch information
messense authored Jul 19, 2023
2 parents 38334d7 + 29df13c commit 99a2a5a
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions maturin/import_hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import shutil
import subprocess
import sys
from contextvars import ContextVar
from importlib import abc
from importlib.machinery import ModuleSpec
from types import ModuleType
Expand All @@ -19,6 +20,11 @@
import tomli as tomllib # type: ignore


# Track if we have already built the package, so we can avoid infinite
# recursion.
_ALREADY_BUILT = ContextVar("_ALREADY_BUILT", default=False)


class Importer(abc.MetaPathFinder):
"""A meta-path importer for the maturin based packages"""

Expand All @@ -34,6 +40,10 @@ def find_spec(
) -> ModuleSpec | None:
if fullname in sys.modules:
return None
if _ALREADY_BUILT.get():
# At this point we'll just import normally.
return None

mod_parts = fullname.split(".")
module_name = mod_parts[-1]

Expand Down Expand Up @@ -74,7 +84,13 @@ def __init__(self, fullname: str):
self.fullname = fullname

def load_module(self, fullname: str) -> ModuleType:
return importlib.import_module(self.fullname)
# By the time we're loading, the package should've already been built
# by the previous step of finding the spec.
old_value = _ALREADY_BUILT.set(True)
try:
return importlib.import_module(self.fullname)
finally:
_ALREADY_BUILT.reset(old_value)


def _is_cargo_project(cargo_toml: pathlib.Path, module_name: str) -> bool:
Expand Down Expand Up @@ -150,7 +166,7 @@ def install(bindings: str | None = None, release: bool = False) -> Importer | No
if _have_importer():
return None
importer = Importer(bindings=bindings, release=release)
sys.meta_path.append(importer)
sys.meta_path.insert(0, importer)
return importer


Expand Down

0 comments on commit 99a2a5a

Please sign in to comment.