[Python-Dev] PEP 8: Discourage named lambdas?

Steven D'Aprano steve at pearwood.info
Sun May 4 11:36:50 CEST 2008


On Sat, 3 May 2008 08:27:27 pm Nick Coghlan wrote:
> Samuele Pedroni wrote:
> > I found only an example in my personal recent code:
> >
> > START = "<!-- *db-payload-start* -->"
> > END = "<!-- *db-payload-end* -->"
> > TITLEPATTERN = lambda s: "<title>%s</title>" % s
> >
> > this three are later used in a very few .find() and .replace()
> > expressions in the same module. I suppose my point is that while I
> > agree it should be discouraged and is really silly to do it for the
> > few chars gain, it can be used to some effect in very rare cases.
>
> The way that's written currently, I think I could *very* easily miss
> the fact that TITLEPATTERN is a callable while glancing over the code
> (and be very confused if I later saw it being called or passed as a
> callback).

I think you're exaggerating a tad here. Why would you be "very confused" 
when you see TITLEPATTERN() or foo(callback=TITLEPATTERN)? What else 
would TITLEPATTERN be but a callable when it's being used as a 
callable?


> Converting to a def makes it obvious that one of these lines is not
> like the others:

Do you get confused by factory functions?

(or for that matter callable class instances, types, etc.)

TITLEPATTERN = factory(args)  # note the lack of def
... lots of code ...
foo(callback=TITLEPATTERN)  # Note: TITLEPATTERN is a callable

I think that if I argued that factory functions were bad because "I 
think I could *very* easily miss the fact that TITLEPATTERN is a 
callable while glancing over the code (and be very confused if I later 
saw it being called or passed as a callback)", most people would 
dismiss the concern and tell me it was my problem. It certainly isn't a 
good reason for discouraging factory functions, and I don't think it 
should be considered a good reason for discouraging lambdas.



-- 
Steven D'Aprano


More information about the Python-Dev mailing list