Skip to content

Instantly share code, notes, and snippets.

@wbond
Last active August 14, 2020 18:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wbond/9c847f9c5d8839b2c9cc1979050926d6 to your computer and use it in GitHub Desktop.
Save wbond/9c847f9c5d8839b2c9cc1979050926d6 to your computer and use it in GitHub Desktop.
How to monkey patch a Python module with code from another location
import importlib
import os
__pkg_path = os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
'Packages',
'Package Control',
'package_control'
)
__file_path = os.path.join(__pkg_path, '__init__.py')
__loader__ = importlib.machinery.SourceFileLoader('package_control', __file_path)
__file__ = __file_path
__package__ = 'package_control'
__path__ = [__pkg_path]
with open(__file_path, 'r', encoding='utf-8') as __f:
__code = compile(__f.read(), '__init__.py', 'exec')
__data = {}
exec(__code, __data)
globals().update(__data)
__spec__.loader = __loader__
__spec__.origin = __file__
__spec__.cached = None
# variables we used
del globals()['__data']
del globals()['__code']
del globals()['__f']
del globals()['__file_path']
del globals()['__pkg_path']
# imports
del globals()['os']
del globals()['importlib']
# out-dated internals
del globals()['__cached__']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment