MartinThoma / flake8-simplify

❄ A flake8 plugin that helps you to simplify code
MIT License
187 stars 19 forks source link

SIM401 should not apply to non-constant default values #166

Open thomasdesr opened 1 year ago

thomasdesr commented 1 year ago

Version:

flake8-simplify==0.19.3

Desired change

Explanation

When the default value in SIM401 statement isn't constant, it may be arbitrarily expensive to calculate if moved into a get. This is not something that can be simplified because python will eagerly evaluate the value in order to execute the get

Example

import asyncio

async def some_async_func():
    await asyncio.sleep(10)

async def foo():
    d = {"key": "value"}
    key = "key"

    if key in d:
        value = d[key]
    else:
        value = await some_async_func()

    return value

Believes it can be simplified to:

import asyncio

async def some_async_func():
    await asyncio.sleep(10)

async def foo():
    d = {"key": "value"}
    key = "key"

    value = d.get(key, await some_async_func())

    return value

However these two are not interchangeable as some_async_func() may be arbitrarily expensive as demonstrated here by the asyncio.sleep(10)