Swap two objects in python

Swapping the contents of two objects in python is so simple you wouldn’t believe.

// yes, it's as simple as reassigning them.
a,b = b,a

So how does this work?
1. First, the right-hand side b,a is evaluated: this means a tuple of two elements is created in memory. The two elements are the objects designated by the identifiers b and a, that existed before the instruction was encountered.

After the creation of this tuple, no assignments of this tuple object have been made yet.

2. Then, the left-hand side is evaluated: this means the tuple is assigned to the left-hand side. Since the left-hand side is composed of two identifiers, the tuple is unpacked in order to assign the first identifier a to the first element of the tuple (the object that was formerly b before the swap) and the second identifier b is assigned to the second element of the tuple (the object that was formerly a before the swap).
This mechanism has effectively swapped the objects assigned to the identifiers a and b.


Quick and Dirty – Indexing Numpy Arrays

Working with arrays can be a bit confusing to begin with. Here’s a quick and dirty array indexing guide to make sure you never get confused.

test = np.array([[ 0, 1, 2, 3, 4],
 [ 5, 6, 7, 8, 9],
 [10, 11, 12, 13, 14]])

Select the third row (row #2):

print test[2]

>> [10 11 12 13 14]

Select row 0 and 1:

print test[:2]

>> [[0 1 2 3 4]
 [5 6 7 8 9]]

Select the last row:

print test[-1]

>> [10 11 12 13 14]

Select column 2:

print test[:,2]

>> [ 2  7 12]
Select elements 0 and 1 in column 2:
print test [0:2, 2]

>> [2 7]

Copying numpy arrays vs. copying lists

Today’s daily pitfall celebrates array copying. In a previous post, we talked about copying lists. If you’re using a numpy array (ndarray), however, the correct way to do it is using numpy’s convenient copy function.

import numpy as np
new_ndarray = np.copy(old_ndarray)

If you try using standard list copying methods – it won’t work, but Python won’t throw an exception, either. Took 30 minutes of algorithm debugging mixed in with a healthy dose of profanity before I tracked down the problem.

new_ndarray = old_ndarray[:]  # please don't do this

How To Unversion A TortoiseSVN Folder

Sharing a fun little hack I just discovered!

When trying to unversion a TortoiseSVN folder, we can do it in two ways:
1. Iterate recursively over folders and subfolders to remove the .svn folder, OR:
2. Right-click on a working copy and choose “Export…” from the context menu. When asked to choose a library, select the same library as the working copy.

This will overwrite the versioned copy with a clean, unversioned one, effectively unversioning the project!

More details at the TortoiseSVN site

Django Dynamic Formset JQuery Library

Django Dynamic Formset JQuery Library

I spent a while searching for a code snippet that would allow the user to dynamically add fields to a form. For instance, if you want to enter several individual items, but don’t know in advance how many…

The perfect snippet eventually led me to a full-fledged jQuery library, for Javascript over Django. Check it out!

Django Template Error – Reverse Template Not Found

Running into a strange django error:

“Reverse for ” with arguments ‘()’ and keyword arguments ‘{}’ not found. ”

This error appeared mysteriously when porting a working project from one computer to another. The first computer was running Python 2.7.1, the second – Python 2.7.2. All other project settings were identical.

For the original computer (Python 2.7.1), the following settings:

<a href="{% url 'display_rulelist' %}"><span class="numbertxt"> Rule List </span>


url(r'^rulelist/$', rulelist.views.display_rulelist,  name = 'display_rulelist')

worked correctly, with no errors. These did NOT work for Python 2.7.2!

For the new computer (Python 2.7.2),

<a href="{% url display_rulelist %}"><span class="numbertxt"> Rule List </span>

removing the apostrophes solved the problem.

I tried going back to the first version and removing the apostrophes as well, but after making the change – the first project no longer worked.

All I can recommend: when running into this error, try both versions!


It was pointed out to me (see comments below) that the url formatting was updated between django 1.4.x and django 1.5. I had completely overlooked that the django versions were different, but so they were: the first project had run django 1.5, and the second: django 1.4.3. Beware of old django versions, users-who-work-on-more than one computer! BEWAAAARE!

Adding CSS templates to Django – A Tutorial for Dummies

I have seen a lot of pages and stackoverflow questions that just want to know… how in hell do I get a CSS template to work with Django, even on a basic level? I found the official documentation for Django static files a bit confusing. So I’ve laid out the steps here, along with some basic tips. This will work for offline development scenarios – I haven’t deployed my project on a *real* server yet. 😉

Without further ado, here we go:

  1. The default location for your static files (CSS style sheets, images) is per app: for each app, create a static subdirectory, and put all your static files there. These apps need to be listed in your INSTALLED APPS setting.
  2. Place your statics files in the appropriate directory. Here the *.css files for app books are located in the static subdirectory, and the images are located in a dedicated images subdirectory within .
  3. Directory Structure

  4. Add django.contrib.staticfiles to your INSTALLED_APPS, in your settings.py file (if it isn’t there already).
  6. If necessary, add explicit local paths to STATICFILES_DIRS in settings.py
  7. # URL prefix for static files.
    # Example: "http://example.com/static/", "http://static.example.com/"
    STATIC_URL = '/static/'
    # Additional locations of static files
        # Put strings here, like "/home/html/static" or "C:/www/django/static".
        # Always use forward slashes, even on Windows.
        # Don't forget to use absolute paths, not relative paths.
  8. When you refer to the files in your templates, you will use the tag {{ STATIC_URL }}. Examples for a CSS stylesheet and an image:
    Display Authors
        	<link href="{{ STATIC_URL }}style1.css" rel="stylesheet" type="text/css" />
    <img alt="" src="{{ STATIC_URL }}images/photo.jpg" />
  10. As shown above, CSS tags are placed below the title tag.
  11. This should work now. Good luck!