The Samurai Principle

Bruno Desthuilliers bdesth.quelquechose at
Tue Sep 7 22:06:37 CEST 2010

Phlip a écrit :
> On Sep 7, 10:12 am, Bruno Desthuilliers <bruno.
> 42.desthuilli... at websiteburo.invalid> wrote:
>> Phlip a écrit :
>>> Back to the topic, I tend to do this:
>>>   for record in Model.objects.filter(pk=42):
>>>      return record
>>>   return sentinel
>> WTF alert here...
> I don't see how anyone could WTF that. Are you pretending to be a newb
> who doesn't understanding it? F'em.

F'... newbies is definitly not the pythonic mindset. Python's mindset is
about doing the most obvious thing, no trying to be smart. The obvious
code here is:

   return Model.objects.get(pk=42)
except Model.DoesNotExist:
   return sentinel

so yes, your above snippet is bordering on WTF since it's not immediatly
obvious - it takes at least one more second for me to parse, and I'm
definitly not a Python nor Django newbie. That's something I'd
immediatly rewrite if I had to work on this code.

> I would guess that Django provides some basic rules for avoiding name
> collisions.

yes : common sense.

> Nobody should call a field "pk__in"

Nope, but "default" - which would be the obvious keyword here - is also
a perfectly legitimate field name.

>> But if you feel like you found the correct name, you can of course
>> monkeypatch queryset !-)
> Know I gotta learn to add a new method to an existing class!

It's as straightforward as possible once you know Python's object model:

def somefunc(self, whatever):

import somemodule
somemodule.SomeClass.mymethod = somefunc

More information about the Python-list mailing list