Skip to content

Instantly share code, notes, and snippets.

@dutc
Created January 25, 2016 06:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dutc/0f7498451d98e3114268 to your computer and use it in GitHub Desktop.
Save dutc/0f7498451d98e3114268 to your computer and use it in GitHub Desktop.
simple import hook for renaming modules
from importlib import import_module
from sys import modules
from warnings import warn
from datetime import date, timedelta
from collections import namedtuple
class RenameHook:
def __init__(self, registry):
self.registry = registry
def find_module(self, fullname, path=None):
if fullname in self.registry:
entry = self.registry[fullname]
if len(entry) == 4:
warning_date, exception_date, new_name, old_name = entry
else:
warning_date = date.today()
exception_date = date.today() + timedelta(1)
new_name = entry
msg = ' '.join(['{} has been moved to {} as of {:%Y-%m-%d};',
'it will no longer be available after {:%Y-%m-%d}',
'please update your imports'])
msg = msg.format(fullname, new_name, warning_date, exception_date)
if date.today() >= exception_date:
raise ImportError(msg)
elif date.today() >= warning_date:
warn(msg, DeprecationWarning)
return self
def load_module(self, fullname):
entry = self.registry[fullname]
if len(entry) == 4:
new_name = entry.new_name
else:
new_name = entry
mod = import_module(new_name)
modules[fullname] = mod
return mod
RenamedModule = namedtuple('RenamedModule', 'from_date to_date new_name old_name')
if __name__ != '__main__':
registry = {'moth': RenamedModule(date(2015, 4, 1), date(2016, 4, 1),
'math', 'moth'),
'random': 'numpy.random',
'linalg': 'numpy.linalg' }
import sys
sys.meta_path = [RenameHook(registry)] + sys.meta_path
@dutc
Copy link
Author

dutc commented Jan 25, 2016

Run:

$ python - Wd
>>> import renamehook
>>> import linalg
>>> import math

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment