Skip to content

Commit

Permalink
Implement find_spec (#129)
Browse files Browse the repository at this point in the history
* Quiet down warnings about find_spec

* version
  • Loading branch information
peterebden committed Mar 13, 2024
1 parent e813f77 commit 2cac028
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
4 changes: 4 additions & 0 deletions tools/ChangeLog
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
Version 1.2.1
-------------
* Quieten warnings from ModuleDirImport / SoImport in newer Python versions

Version 1.2.0
-------------
* Upgrade importlib-metadata to 6.8.0 (#122) - note that this increases the
Expand Down
2 changes: 1 addition & 1 deletion tools/VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.2.0
1.2.1
20 changes: 18 additions & 2 deletions tools/please_pex/pex/pex_main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""Zipfile entry point which supports auto-extracting itself based on zip-safety."""

from importlib import import_module
from importlib.abc import MetaPathFinder
from importlib.util import spec_from_loader
from zipfile import ZipFile, ZipInfo, is_zipfile
import os
import runpy
Expand Down Expand Up @@ -109,7 +111,7 @@ def _extract_member(self, member, targetpath, pwd):
os.chmod(targetpath, attr)
return targetpath

class SoImport(object):
class SoImport(MetaPathFinder):
"""So import. Much binary. Such dynamic. Wow."""

def __init__(self):
Expand All @@ -136,6 +138,13 @@ def __init__(self):
if self.modules:
self.zf = zf

def find_spec(self, name, path, target=None):
"""Implements abc.MetaPathFinder."""
loader = self.find_module(name, path)
if loader is None:
return None
return spec_from_loader(name, loader)

def find_module(self, fullname, path=None):
"""Attempt to locate module. Returns self if found, None if not."""
if fullname in self.modules:
Expand Down Expand Up @@ -167,7 +176,7 @@ def splitext(self, path):
return None, None


class ModuleDirImport(object):
class ModuleDirImport(MetaPathFinder):
"""Handles imports to a directory equivalently to them being at the top level.
This means that if one writes `import third_party.python.six`, it's imported like `import six`,
Expand All @@ -178,6 +187,13 @@ class ModuleDirImport(object):
def __init__(self, module_dir=MODULE_DIR):
self.prefix = module_dir.replace('/', '.') + '.'

def find_spec(self, name, path, target=None):
"""Implements abc.MetaPathFinder."""
loader = self.find_module(name, path)
if loader is None:
return None
return spec_from_loader(name, loader)

def find_module(self, fullname, path=None):
"""Attempt to locate module. Returns self if found, None if not."""
if fullname.startswith(self.prefix):
Expand Down

0 comments on commit 2cac028

Please sign in to comment.