[Python-ideas] Adding __getter__ to compliment __iter__.

Ron Adam ron3200 at gmail.com
Mon Jul 22 07:16:58 CEST 2013



On 07/18/2013 11:59 PM, Nick Coghlan wrote:
> On 19 July 2013 00:29, Ron Adam <ron3200 at gmail.com> wrote:
>> I was thinking a generator would be more efficient if it's called many
>> times.  But I think this is easier to understand.  If there is more interest
>> we can test both to see how much of a difference it makes.
>
> Suspending and resuming a generator is quite an expensive operation.
> send() has the triple whammy of method call + resume generator +
> suspend generator, so it's unlikely to outperform a simple method call
> (even one that redirects to another method).

Hmmm  I think the generators did work faster in earlier versions on python 
run on older computers.  Maybe, it's because today's python, and computers, 
use cache's much better, so there isn't as much of a difference.


> Independent of performance though, I think the mutable sequence API
> inspired append(), extend() and += are a better API for what you're
> trying to achieve than "send", so it doesn't make sense to me to try
> to shoehorn this into the generator API.

'+=' is a additive/append type of operation.  What is needed for cat... or 
sum is an extend operation.  I don't think '+=' is right for that.  And it 
is already used quite a lot in python programs.

A much less used symbol is __lshift__ , '<<'.  I think it also carries the 
right meaning of sending the value on the right to the object on the left. 
  And not have too much other meanings in the same context.  Binary left 
shift is hardly ever used in higher level programs.


With that the example sum function can become this...

  def sum_items(start, items):
     try:
         c = Cat()
         return c << start << items << c.end
     except:
         for n in items:
             start += n
         return start

Quite a bit simpler and shorter.  Can work with strings, lists, tuples, and 
any type that can be converted to a list.  It returns a modified start if 
it's mutable, or a new object of the start type if it immutable.  (or a sum 
of values in a iterable.)


Explicit string concatenation...

     >>> c = Cat()
     >>> c << "One " << "Two " << "Three!" << c.end
     'One Two Three!'

Good for a temporary buffer, and possibly have other uses with other types.


And interesting alternative possibility is a concatenation_comprehension. 
Or cat_comp for short.

     >>> ("One " << "Two " << "Three!")
     'One Two Three!'

It would work with other types as well.  You would almost always want the 
parentheses any ways.

Cheers,
    Ron




More information about the Python-ideas mailing list