> ## 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.

# Use Named Expression

#### Sourcery refactoring id: `use-named-expression`

#### Description:

Merge assignment followed by conditional check using a named expression.

#### Before:

```python
env_base = os.environ.get("PYTHONUSERBASE", None)
if env_base:
    return env_base
```

```python
chunk = file.read(8192)
while chunk:
    process(chunk)
    chunk = file.read(8192)
```

#### After:

```python
if env_base := os.environ.get("PYTHONUSERBASE", None):
    return env_base
```

```python
while chunk := file.read(8192):
    process(chunk)
```

#### Explanation:

Assignment (or named) expressions were introduced into Python 3.8 via
[PEP 572](https://www.python.org/dev/peps/pep-0572/). They are a way of
assigning to a variable inside an expression. The value of such a named
expression is the same as the incorporated expression, with the additional
side-effect that the target is assigned that value. For example:

```python
while chunk := file.read(8192):
    process(chunk)
```

The named expression here returns the result of `file.read()` to decide whether
to continue the `while` loop, and also assigns the result to `chunk` so that it
can be processed. Using a named expression to merge an assignment followed
immediately by a condition checking the result leads to cleaner code - once you
know the syntax it can be understood at a glance. It can also lead to
simplification of more complex expressions involving if - for example the below:

Before:

```python
if self._is_special:
    ans = self._check_nans(context=context)
    if ans:
        return ans
```

After applying the named expression then merging the if conditions:

```python
if self._is_special and (ans := self._check_nans(context=context)):
    return ans
```
