views:

299

answers:

2

Is there a benefit to passing a string in your url patters vs a function instance? It seems like it could be optimized to not actually load the function until it is needed, but is this in fact true?

from django.conf.urls.defaults import *
from myapp.views import myView

urlpatterns = patterns('',
    # as a string
    url(r'^as-string/$', "myapp.views.myView"),

    # Uploading photos
    url(r'^as-instance/$', myView),

)

edit: If it's true that it doesn't import until they're needed, then it would be an optimization for memory, but non-existant functions and other errors would not be raised until you actually try to visit the url.

Of course that isn't an issue if you write tests though ;)

+1  A: 

Perusing the source to RegexURLPattern (which is what defaults.url is using under the covers) confirms that the import only happens when and if needed, and so your ideas are correct: it's a slight optimization but does require thorough tests!

Alex Martelli
+7  A: 

The main benefit is that when you're working with the actual callable object you can do things like apply decorators to it in the URLConf. So you can do things like:

from django.conf.urls.defaults import *
from django.contrib.auth.decorators import login_required

from some_module import some_view

urlpatterns = patterns('',
                       (r'^some_url/$', some_view),
                       (r'^some_other_url/$', login_required(some_view)))

etc.

This lets you have decorators which are only applied to a view when you specifically want them to, rather than decorating in the views file and then having to live with it always having that decorator applied.

James Bennett
I like that trick I'll have to do that from now on :)
Jiaaro