[Python-ideas] Where-statement (Proposal for function expressions)

Gerald Britton gerald.britton at gmail.com
Fri Jul 17 22:28:40 CEST 2009


I often time my code and often find that removing function calls
"where" possible actually makes a measurable difference.  This is
especially the case with little getters and setters in class defs.

Anyway, I like the "where" idea not because of real or imagined
performance gains, but because of its cleanness when expressing
problems.  A big use for me would be in list comprehensions.  In one
project I work on, I see things like:

for i in [item in self.someobject.get_generator() if self.important_test(item)]

and other really long object references.

which I would like to write:

mylist =  [item in f if g(item)] where:
    f = self.someobject.get_generator()
    g = self.important_test


To my eyes, the first is harder to read than the second one.  Of
course I can do this:

    f = self.someobject.get_generator()
    g = self.important_test
    mylist =  [item in f if g(item)]:


but then "f" and "g" pollute the calling context's namespace.

Anyway, I don't have a strong preference, just a "nice to have" feeling.

On Fri, Jul 17, 2009 at 10:24 AM, Steven D'Aprano<steve at pearwood.info> wrote:
> On Fri, 17 Jul 2009 11:25:15 pm Gerald Britton wrote:
>> Sometimes I use helper functions to make things easier to read.
>> However, I don't like unnecessary function calls since they are
>> expensive in Python compared to other languages.
>
> That's only a problem if:
>
> (1) Your code actually is too slow; and
>
> (2) You have profiled your code and discovered that the biggest
> contributor to your code's slowness is the cost of calling functions,
> not the execution time of the functions.
>
> Unless both of these cases hold, then I suggest you are guilty of
> premature optimization. Possibly even pessimation -- given the
> complexities of CPU caches, memory, swap, etc, it's possible that your
> code could be *slower*, not faster, due to your "optimization".
>
> People's intuitions about what's fast and what's slow in Python code are
> often completely at odds with reality. Unless you actually have a
> problem with slow code that needs solving, my advice is to not worry
> about it. Use good algorithms, use tried and tested fast data
> structures, and worry about micro-optimizations when you *actually*
> need them.
>
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>



-- 
Gerald Britton



More information about the Python-ideas mailing list