Skip to content

Instantly share code, notes, and snippets.

@VITIMan
Created August 30, 2017 14:16
Show Gist options
  • Save VITIMan/87f7b89fe5cfc935e571d89531b780bf to your computer and use it in GitHub Desktop.
Save VITIMan/87f7b89fe5cfc935e571d89531b780bf to your computer and use it in GitHub Desktop.
Some dynamic imports snippets
"""
# From: https://stackoverflow.com/a/30941292
# Standard import
import importlib
# Load "module.submodule.MyClass"
MyClass = getattr(importlib.import_module("module.submodule"), "MyClass")
# Instantiate the class (pass arguments to the constructor, if needed)
instance = MyClass()
"""
class ClassAType():
pass
class ClassBType():
pass
class SomeClass()
# ...
def some_method(self, **kwargs):
module = importlib.import_module(__name__)
s = getattr(
module, "Class{}Type".format(
self.obj["some_type"].upper()))(self.obj)
return s.other_method(**kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment