Created
August 28, 2018 16:54
-
-
Save jpic/4dda11a23fa7e0d7667410650558b588 to your computer and use it in GitHub Desktop.
Import any python callback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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