Skip to content

Instantly share code, notes, and snippets.

@liviaerxin
Last active July 23, 2020 02:25
Show Gist options
  • Save liviaerxin/5cba8b5d132df167a86be5bbb4cb08f9 to your computer and use it in GitHub Desktop.
Save liviaerxin/5cba8b5d132df167a86be5bbb4cb08f9 to your computer and use it in GitHub Desktop.
Hack Python Imported Module
# hack tensorflow.compat.v2 imported module name as tensorflow
# first
import sys
import importlib.util
name = "tensorflow.compat.v2"
spec = importlib.util.find_spec(name)
if spec is None:
print(f"can't find the {name} module")
else:
# If you chose to perform the actual import ...
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# Adding the module to sys.modules is optional.
sys.modules["tensorflow"] = module
# then try import
import tensorflow
print(tensorflow.__file__)
tensorflow.compat.v1.enable_v2_behavior()
tensorflow.__version__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment