Last active
December 15, 2015 00:08
-
-
Save public/5170465 to your computer and use it in GitHub Desktop.
Prevent loading of pyc files when the py file has disappeared.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import imp | |
import os | |
import os.path | |
import stat | |
import sys | |
class pycSanity(object): | |
def __new__(cls, *args): | |
obj = super(pycSanity, cls).__new__(cls) | |
obj.args = args | |
return obj | |
@classmethod | |
def find_module(cls, module_name, package_path): | |
try: | |
return cls(module_name, *imp.find_module(module_name, package_path)) | |
except ImportError as exc: | |
return None | |
def load_module(self, fullname): | |
load_pathname = self.args[2] | |
if load_pathname[:-1].endswith('.py') and os.path.isfile(load_pathname): | |
source_name = os.path.splitext(load_pathname)[0] + '.py' | |
if not os.path.isfile(source_name): | |
return None | |
return ( | |
sys.modules.get(self.args[0]) or | |
imp.load_module(*self.args) | |
) | |
sys.meta_path.append(pycSanity) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment