[New-bugs-announce] [issue41795] Allow assignment in yield statement

Richard Neumann report at bugs.python.org
Wed Sep 16 04:46:53 EDT 2020


New submission from Richard Neumann <mail at richard-neumann.de>:

I often write factory (deserialization) methods for ORM models for web application backends that produce a number of records (ORM model instances) of itself and related database tables:

    @classmethod
    def from_json(cls, json):
        """Yields records from a JSON-ish dict."""
        modules = json.pop('modules', None) or ()
        order = super().from_json(json)
        yield order

        for module in modules:
            yield OrderedModule(order=order, module=Module(module))

This yields the main record "order" and related records from OrderedModules, which have a foreign key to Order.
Thusly I can save all records by:

    for record in Order.from_json(json):
        record.save()

Since I have several of those deserialization functions for multiple tables in multiple databases, it'd be nice to reduce the amount of code with some extra syntactic sugar, like:

    @classmethod
    def from_json(cls, json):
        """Yields records from a JSON-ish dict."""
        modules = json.pop('modules', None) or ()
        yield order = super().from_json(json)  # Assignment via "="

        for module in modules:
            yield OrderedModule(order=order, module=Module(module))

or:

    @classmethod
    def from_json(cls, json):
        """Yields records from a JSON-ish dict."""
        modules = json.pop('modules', None) or ()
        yield order := super().from_json(json)  # Assignment via ":="

        for module in modules:
            yield OrderedModule(order=order, module=Module(module))

I therefor propose to allow assignment of names in generator-like yield statements as described above.

----------
messages: 376979
nosy: conqp
priority: normal
severity: normal
status: open
title: Allow assignment in yield statement
type: enhancement
versions: Python 3.10

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue41795>
_______________________________________


More information about the New-bugs-announce mailing list