Skip to content


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Update chapter04.rst

The locals trick is something almost always best not-done, and can be an especially dangerous crutch for new developers to hold on to.

I feel it doesn't add enough to warrant inclusion in an intro book.
  • Loading branch information...
commit 67548ae7bd92d69ff7fa5960bd1bfbce73b1288d 1 parent fd9362a
Jacob Burch authored
Showing with 0 additions and 43 deletions.
  1. +0 −43 chapter04.rst
43 chapter04.rst
@@ -1225,49 +1225,6 @@ template to use. The second argument, if given, should be a dictionary
to use in creating a ``Context`` for that template. If you don't
provide a second argument, ``render_to_response()`` will use an empty dictionary.
-The locals() Trick
-Consider our latest incarnation of ``current_datetime``::
- def current_datetime(request):
- now =
- return render_to_response('current_datetime.html', {'current_date': now})
-Many times, as in this example, you'll find yourself calculating some values,
-storing them in variables (e.g., ``now`` in the preceding code), and sending
-those variables to the template. Particularly lazy programmers should note that
-it's slightly redundant to have to give names for temporary variables *and* give
-names for the template variables. Not only is it redundant, but also it's extra
-So if you're one of those lazy programmers and you like keeping code
-particularly concise, you can take advantage of a built-in Python function
-called ``locals()``. It returns a dictionary mapping all local
-variable names to their values. Thus, the preceding view could be
-rewritten like so::
- def current_datetime(request):
- current_date =
- return render_to_response('current_datetime.html', locals())
-Here, instead of manually specifying the context dictionary as before, we
-pass the value of ``locals()``, which will include all variables
-defined at that point in the function's execution. As a consequence, we've
-renamed the ``now`` variable to ``current_date``, because that's the variable
-name that the template expects. In this example, ``locals()`` doesn't offer a
-*huge* improvement, but this technique can save you some typing if you have
-several template variables to define--or if you're lazy.
-One thing to watch out for when using ``locals()`` is that it includes *every*
-local variable, which may comprise more variables than you actually want your
-template to have access to. In the previous example, ``locals()`` will also
-include ``request``. Whether this matters to you depends on your application.
-A final thing to consider is that ``locals()`` incurs a small bit of overhead,
-because when you call it, Python has to create the dictionary dynamically. If
-you specify the context dictionary manually, you avoid this overhead.
Subdirectories in get_template()
Please sign in to comment.
Something went wrong with that request. Please try again.