[Python-ideas] "While" suggestion

Roman Susi rnd at onego.ru
Wed Jul 30 08:25:59 CEST 2008


Steven Bethard wrote:
> On Tue, Jul 29, 2008 at 8:55 PM, Terry Reedy <tjreedy at udel.edu> wrote:
>> Steven Bethard wrote:
>>> On Tue, Jul 29, 2008 at 3:19 PM, Terry Reedy <tjreedy at udel.edu> wrote:
>>>> Roman Susi wrote:
>>>>> Python already has dict/list literals + list comprehensions.
>>>> Better to think that Python has generator expressions which can be used
>>>> in list, set, and dict comprehensions (the latter two in 3.0 and maybe 2.6).
>>> You probably don't want to think about it that way - a list/set/dict
>>> comprehension does not actually create a generator.
>> Yes I do.  For normal purposes, in 3.0, [genexp] == list(genexp), and so on.
>>  That it do something else internally for efficiency is implementation
>> detail, not semantics.

First of all, the difference in semantics is not that crucial for the
point I made (no extra syntax for Python built-in "query language").
Both ways (list comprehensions and generators) are ways to abstract
iterative processing of items of some data structures (they are
iterative) where generators are much more generic.

The problem is not on the result side. Syntax proposed for while/until
and other possible additions (try-except, with) are basically the
filters in the pipeline which are possible to do with functional
approach (using generator protocol or not and whether or not it is good
"laziness" - is a matter of implementation) without introducing obscure
syntactic additions and new or reused keywords. As someone pointed out,
maybe more advanced itertools / "gentools" can achieve desired results
without loosing efficiency but helping readable iterators/generators
pipeline construction for modeling query languages.

-Roman

> But the semantics are pretty different. The semantics are basically:
> 
>     def _(seq):
>         _1 = []
>         for x in seq:
>             _1.append(<expression with x>)
>         return _1
>     return _(seq)
> 
>     def _(seq):
>         for x in seq:
>             yield <expression with x>
>     return list(_(seq))
> 
> Yes, they produce the same results, but semantically they're
> different. In one case, a list is created and items are appended to it
> and then that list is returned. In the other case, a generator object
> is created, and then that generator is repeatedly resumed to yield
> items by the list() constructor.

> 
> I think it's fine to say they achieve the same result, but I think
> saying they're really the same thing is a mistake.
> 
> Steve
> 
> P.S. Yes, it's executed in a different scope - that's why the code I
> showed you before had to do ``dict_comp.__code__.co_consts[1]``
> instead of just ``dict_comp.__code__``.
> 
> 




More information about the Python-ideas mailing list