On Tue, Jun 29, 2021 at 7:51 AM Max Shouman <shouman....@gmail.com> wrote:
>
> This is more of a syntactic sugar than an actual new feature, but...
> Exactly, 'but' is the idea: a special keyword to be used in for statements to 
> exclude values from the iterable.
>
> E.g., when iterating over a generator:
> >>> for i in range(0, 10) but (2, 8):
> would implicitly create a new generator comprehensively, as in:
> >>> for i in (j for j in range(0, 10) if j not in [2, 8]):
>
> It might not add such a feature to justify the definition of a but_stmt in 
> python.gram, but it's fully compliant with Python's philosophy of concise, 
> clear and elegant code.
>
> #road to a programming natural language (jk)

Python currently has 35 keywords. To justify a 36th, there needs to be
a *lot* of benefit. Instead, perhaps it'd be worth devising your own
range() type which is capable of subtraction?

_range = range
class range:
    def __init__(self, *args, exclude=()):
        self.basis = _range(*args)
        self.excludes = exclude
    def __sub__(self, other):
        return type(self)(r.start, r.stop, r.step,
excludes=self.exclude + other)
    def __iter__(self):
        for val in self.basis:
            if val not in self.excludes: yield val

Then you can write this:

for i in range(0, 10) - (2, 8):
    ...

Tada! No new keyword needed, and it reads better than "but" does
("except for" would be how English would normally write that).

ChrisA
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/MHRVEWN5FUMWVV5BCAEALEN6WGJ5L4C2/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to