On Mon, Oct 14, 2019 at 9:39 AM Steven D'Aprano <st...@pearwood.info> wrote:
>
> On Sun, Oct 13, 2019 at 03:59:19PM +0200, Anders Hovmöller wrote:
>
> > A thing to consider here is that the with block in python doesn't introduce 
> > a scope so after:
> >
> > with foo() as bar:
> >     a = 2
> >     b = 3
> >
> > now bar, a and b are all available in the scope.
>
> That's not a problem. We could introduce a rule that when the with block
> is part of an assignment, the with block runs in a seperate scope.
>
> A bigger problem is that this would be the first statement which
> returns a value (as opposed to having an effect via side-effects, like
> the class and def statements), and it would only be usable in
> assignments:
>
> spam = with eggs() as cheese:
>     ...
>
> but not:
>
> items = [x, y, with eggs() as cheese: ... , z]
>
>

Scope... return value... this sounds familiar. What if this were
actually a function? You'd have to implement build_choices
appropriately for this to work, but you'd need to do that for the
context manager anyway.

    @build_choices('Restaurant')
    def restaurant_choices(cb):
        # Get of nonexistent attr auto-generates matching entry.
        cb.BURGER_KING
        cb.FIVE_GUYS
        # Returned value is a ChoiceItem that implements __mod__ to return a
        # new ChoiceItem instance w/ substituted label.
        cb.MCDONALDS %= "McDonald's"

    print(restaurant_choices)
    # RestaurantChoices(
    #  (
    #   ('BURGER_KING', 'Burger King'),
    #   ('FIVE_GUYS', 'Five Guys'),
    #   ('MCDONALDS', "McDonald's")))

    print(RestaurantChoices.BURGER_KING)

To make this work, your build_choices would need to have something like this:

class build_choices:
    def __call__(self, builder):
        builder(self)
        return self

Does that look clean enough?

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/5SHTO7LOKSAIJYBN2P574KKTBGPW3YPV/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to