Python lesson I learned today - use “is None” when you want to check if something exists. I had heard this advice before but it was so easy for me to be a little slutty with my usage of “if not x:”.
Here’s where it hurt:
def get_notes(qs=None):
if not qs:
qs = self.notes.all()
…
The optional qs parameter is for a Django QuerySet ORM object which was intended for some subset of the user’s notes like only files ( self.notes.filter(type=’file’) ). Versatile!
However, if the QuerySet was an empty result set, the “if not qs” evaluated to False. Then qs became the set of all notes. Exactly NOT what I wanted! Wow. Terrible.
The correct condition is “if qs is None” like so:
def get_notes(qs=None):
if qs is None: # no predefined queryset
qs = self.notes.all()
…
Anyways, I hope this helps someone else.
12 Comments
mikeal
“is” is a pointer check rather than a comparison like == or !=.
Another nice little python optimization is that numbers
Matthew Maroon
Yikes, looks like you have a fan there. Being slagged in blogs is fun!
Interesante
The other mistake is reading, taking personally, and then directing attention to that LiveJournal comment, because now that person thinks they got to you and they got some attention for it.
My fault for clicking the link, of course.
Danno
wow. someone really posted that.
sheesh.
wants me to send them a letter bomb?
Rocksteady,
Danno~
Tiago Rodrigues
Well thanks for the tip
Although i already tried starting to work with Python a while ago, time hadn’t allowed me to really practice it (i usually work with PHP). Now with the prospect of a new project (and some freedom of choice) i decided to give Python (and Django) a try, and i just started reading a nice book on it today, so this kind of tip is always useful.
Philip Crow
Well, I have no idea what that even means, so that makes me dumber than you??
mikeal
hrm, my post got mangled after the “greater than” operator I had in the post. I smell a bug
Leah Culver
@ Interesante - agreed and deleted. Sorry for editing a posted entry.
Pete
It was the right move. It is better to be above it all
stubblechin
Good move, Leah.
Brian Rosner
Yeah, I got bitten by this during development. Good thing I had a large dataset that pointed it out to me. Dang, lazy querysets, they make us all lazy
Nick Lewis
About a month ago, I was writing (in Python) an interpreter for a reduced version of PostScript for a class, and made a similar mistake. I was checking whether I had some code to execute, and if so, would interpret it. But my check was just using “if token_code”, rather than “if token_code != None”, so if the bit of code was just a literal 0, it would evaluate as false, and would skip it. I just started a new job working in Perl for the first time, and one of the hardest things is keeping straight what is implicitly true and false. So convenient to not have to be explicit, but only when it ends up *correct*.