[Python-ideas] except expression

Oscar Benjamin oscar.j.benjamin at gmail.com
Wed Feb 19 16:38:29 CET 2014


On 19 February 2014 15:06, Chris Angelico <rosuav at gmail.com> wrote:
> On Thu, Feb 20, 2014 at 1:48 AM, Oscar Benjamin
> <oscar.j.benjamin at gmail.com> wrote:
>> This proposal is similar but it's
>> hard to find the cases that would be simplified by it as they will
>> probably be written in a very different way right now.
>
> If they're written the way you describe, with a "try" block that
> assigns to something and an "except" block that assigns to the exact
> same thing, my script will find them. You might want to disable (by
> commenting out) some of the handlers at the top; the ast.Expr one, in
> particular, tends to generate a lot of spam.

A search through cpython didn't turn up much. There are only two
Subscript nodes found by this script and only this one seems relevant:
http://hg.python.org/cpython/file/9cfb3d1cf0d1/Lib/sysconfig.py#l514

For whatever reason that code just creates a dict with a whole load of
assignments anyway though. Personally I would have written that as a
display so instead of this:

    _CONFIG_VARS = {}
    # Normalized versions of prefix and exec_prefix are handy to have;
    # in fact, these are the standard versions used most places in the
    # Distutils.
    _CONFIG_VARS['prefix'] = _PREFIX
    _CONFIG_VARS['exec_prefix'] = _EXEC_PREFIX
    _CONFIG_VARS['py_version'] = _PY_VERSION
    _CONFIG_VARS['py_version_short'] = _PY_VERSION_SHORT
    _CONFIG_VARS['py_version_nodot'] = _PY_VERSION[0] + _PY_VERSION[2]
    _CONFIG_VARS['installed_base'] = _BASE_PREFIX
    _CONFIG_VARS['base'] = _PREFIX
    _CONFIG_VARS['installed_platbase'] = _BASE_EXEC_PREFIX
    _CONFIG_VARS['platbase'] = _EXEC_PREFIX
    _CONFIG_VARS['projectbase'] = _PROJECT_BASE
    try:
        _CONFIG_VARS['abiflags'] = sys.abiflags
    except AttributeError:
        # sys.abiflags may not be defined on all platforms.
        _CONFIG_VARS['abiflags'] = ''

You could do this:

    _CONFIG_VARS = {
        # Normalized versions of prefix and exec_prefix are handy to have;
        # in fact, these are the standard versions used most places in the
        # Distutils.
        'prefix':_PREFIX,
        'exec_prefix':_EXEC_PREFIX,
        'py_version':_PY_VERSION,
        'py_version_short':_PY_VERSION_SHORT,
        'py_version_nodot':_PY_VERSION[0] + _PY_VERSION[2],
        'installed_base':_BASE_PREFIX,
        'base':_PREFIX,
        'installed_platbase':_BASE_EXEC_PREFIX,
        'platbase':_EXEC_PREFIX,
        'projectbase':_PROJECT_BASE,
        # sys.abiflags may not be defined on all platforms.
        'abiflags':sys.abiflags except AttributeError: ''
    }


Oscar


More information about the Python-ideas mailing list