Skip to content

Instantly share code, notes, and snippets.

@jpic
Created August 28, 2018 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpic/4dda11a23fa7e0d7667410650558b588 to your computer and use it in GitHub Desktop.
Save jpic/4dda11a23fa7e0d7667410650558b588 to your computer and use it in GitHub Desktop.
Import any python callback
"""
Currently with django we can only import an attribute from a module, not a sub-attribute. For example
import_string('foo.models.YourModel') # works
import_string('foo.models.YourModel.objects.update_stats') # doesn't
This snippet fixes that, originally for django-call which has tests.
"""
from django.utils.module_loading import import_string
def import_callback(callback):
parts = callback.split('.')
i = callback.count('.')
while i:
try:
mod = import_string('.'.join(parts[:i + 1]))
except ImportError:
if not i:
raise
i -= 1
else:
ret = mod
while 0 < i < callback.count('.'):
ret = getattr(ret, parts[len(parts) - i])
i -= 1
return ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment