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.

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers  (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/django-developers.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-developers/b3410c61-1c0b-4b23-9419-a799721d3e29%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to