lazy_import_string

51 views
Skip to first unread message

Riccardo Di Virgilio

unread,
Jan 24, 2015, 5:32:17 AM1/24/15
to django-d...@googlegroups.com
Hi, 

I'm riccardo, currently working at Wolfram Reasearch Inc,
I've done some contributions in the past, refactoring django.contrib.gis.measure

In order to speed up loading time of my django application I'm using this code, which I think it can be inserted inside django.utils.module_loading

the reason why I'm using this is because I wanted to speedup my application loading, which was quite slow before, because it was loading a lot of external libraries that are not used when the application is loaded.

with that trick you can define a lazy import and load the module at runtime once, when is needed, if is needed.

this is all the code that is required.

from django.utils.module_loading import import_string
from django.utils.functional import SimpleLazyObject, empty
from functools import partial

class CallableLazyObject(SimpleLazyObject):
    def __call__(self, *args, **kw):
        if self._wrapped is empty:
            self._setup()
        return self._wrapped(*args, **kw)

def lazy_import_string(path):
    return CallableLazyObject(partial(import_string, path))


this piece of code is really easy, but it's very powerful. 
sample usage:

>>> User = lazy_import_string("django.contrib.auth.models.User")

>>> User

<CallableLazyObject: <functools.partial object at 0x10e1f56d8>>

>>> User(username = "foo")

<User: foo>

>>> User._meta

<Options for User>

one last thing.

why SimpleLazyObject do not allow __call__?
without it you cannot use it to import and init objects or call functions.
this is probably a thing to fix for the next release.
Reply all
Reply to author
Forward
0 new messages