Skip to content

Or-If-Exp-Identity

Documentation Index

Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt

Use this file to discover all available pages before exploring further.

Replace if-expression with or

currency = input_currency if input_currency else DEFAULT_CURRENCY
currency = input_currency or DEFAULT_CURRENCY

Here we find ourselves setting a value if it evaluates to True, and otherwise using a default.

The ‘After’ case is a bit easier to read and avoids the duplication of input_currency.

It works because the left-hand side is evaluated first. If it evaluates to true then currency will be set to this and the right-hand side will not be evaluated. If it evaluates to false the right-hand side will be evaluated and currency will be set to DEFAULT_CURRENCY.