Skip to content

Instantly share code, notes, and snippets.

@python012
Created June 26, 2018 08:40
Show Gist options
  • Save python012/e7dfc44805e8b49d582c53cbe33b576a to your computer and use it in GitHub Desktop.
Save python012/e7dfc44805e8b49d582c53cbe33b576a to your computer and use it in GitHub Desktop.
python lib inspect, could help check the target function's caller
import copy
import os
from importlib import import_module
from importlib.util import find_spec as importlib_find
import inspect
def import_string(dotted_path):
"""
Import a dotted module path and return the attribute/class designated by the
last name in the path. Raise ImportError if the import failed.
"""
try:
print("-------------------------------------------------")
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 4)
print('---- called from ' + calframe[1][3] + ' in ' + calframe[1][4][0][6: -2])
print(dotted_path)
print("-------------------------------------------------")
module_path, class_name = dotted_path.rsplit('.', 1)
except ValueError as err:
raise ImportError("%s doesn't look like a module path" % dotted_path) from err
module = import_module(module_path)
try:
return getattr(module, class_name)
except AttributeError as err:
raise ImportError('Module "%s" does not define a "%s" attribute/class' % (
module_path, class_name)
) from err
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment