[issue44276] Replace if-elif-else structure with match-case (PEP634)

Kshitiz Arya report at bugs.python.org
Tue Jun 1 06:22:01 EDT 2021


Kshitiz Arya <aryakshitiz17 at gmail.com> added the comment:

This is a relatively simple example of how this will improve readability of the code.
(This example is form Lib/json/encoder.py)

Original

-------------------------------------------------------------------------
    if isinstance(value, str):
        yield _encoder(value)
    elif value is None:
        yield 'null'
    elif value is True:
        yield 'true'
    elif value is False:
        yield 'false'
    elif isinstance(value, int):
        yield _intstr(value)
    elif isinstance(value, float):
        yield _floatstr(value)
    else:
        if isinstance(value, (list, tuple)):
            chunks = _iterencode_list(value, _current_indent_level)
        elif isinstance(value, dict):
            chunks = _iterencode_dict(value, _current_indent_level)
        else:
            chunks = _iterencode(value, _current_indent_level)
        yield from chunks 
--------------------------------------------------------------------------

Suggested

--------------------------------------------------------------------------
    match value:
        case str():
            yield _encoder(value)
        case None:
            yield 'null'
        case True:
            yield 'true'
        case False:
            yield 'false'
        case int():
            # see comment for int/float in _make_iterencode
            yield _intstr(value)
        case float():
            # see comment for int/float in _make_iterencode
            yield _floatstr(value)
        case _:
            match value:
                case list()|tuple():
                    chunks = _iterencode_list(value, _current_indent_level)
                case dict():
                    chunks = _iterencode_dict(value, _current_indent_level)
                case _:
                    chunks = _iterencode(value, _current_indent_level)
            yield from chunks
----------------------------------------------------------------------------

----------

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


More information about the Python-bugs-list mailing list