Naming things: don’t use reserved words

Tags: python, django

Update: added postfixed-with-underscore examples.

I’m currently cleaning up some code. Some people just cannot spell “p-e-p-8” if their lives depended on it, apparently. Luckily I’m civilized so I only threaten with dismemberment.

Look at this gem I just uncovered:

tg_after = instance.filter.technischegegevensfilter_set.exclude(
    pk=instance.pk).filter(
        datum_vanaf__gt=instance.datum_vanaf).order_by(
            'datum_vanaf')[:1]

Don’t mind about the Dutch in there. Just look at those two filter words in the first two lines. They’re even nicely underneath each other. At least they are now, I first had to fit the 159 characters long line within 78 characters, of course.

In Django, you do sql filtering with .filter(some_condition=42). That’s not what’s happening in the first line, though. There’s a foreign key called filter there! So the first filter is the name of a foreign key and the second filter is the filter method that is used everywhere in Django.

Big confusion. And big chance that someone else that reads the code messes it up somehow.

So... steer clear of common words used in your programming language or framework or whatever. Some examples:

  • Don’t use type as an name. Use customer_type or station_type or whatever. Only use type by itself if you really mean the python build-in. Alternatively you can postfix it with an underscore, so type_
  • Don’t use class. Either use the often-used klass or class_ alternative if you want to keep it short. But why not use css_class if you want to return a css class, for instance?
  • Don’t use filter for Django models. Even if you’re modelling filters that are used for groundwater extraction (as in this case). Call them WaterFilter or so.

So... you can now go and fix your code. You’ve got about 45 minutes before I’m ready sharpening my axe.

blog comments powered by Disqus
 
vanrees.org logo

About me

My name is Reinout van Rees and I work a lot with Python (programming language) and Django (website framework). I live in The Netherlands and I'm happily married to Annie van Rees-Kooiman.

Weblog feeds

Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):