python-3.xflake8

Using a class property as an iterable produces a reassign warning


I need to use an iterable and a loop variable as a class property. But the flake8 checker produces B2020 warning:

easy.py:11:13: B020 Found for loop that reassigns the iterable it is iterating with each iterable value.

If I use a variable for iterable there is OK.

What is wrong?

The warning example:

#!/usr/bin/env python3
"""Example of B020 error."""


class My_Template:
    """My example."""

    def __init__(self, *template):
        """Obviously init."""
        self.all_templates = (1, 2, 3)
        for self.tpl in self.all_templates:
            print(self.tpl)

The flake8 complains about loop variable:

easy.py:11:13: B020 Found for loop that reassigns the iterable it is iterating with each iterable value.

The OK example:

#!/usr/bin/env python3
"""Example of B020 error."""


class My_Template:
    """My example."""

    def __init__(self, *template):
        """Obviously init."""
        all_templates = (1, 2, 3)
        for self.tpl in all_templates:
            print(self.tpl)

Solution

  • It's a known issue:

    https://github.com/PyCQA/flake8-bugbear/issues/248

    Understandably flake8-bugbear developers are a bit unwilling to fix this as it's not very common to use an instance attribute as the loop variable. It's also not really needed. You can simply use a normal loop variable:

    class My_Template:
        def __init__(self, *template):
            self.all_templates = (1, 2, 3)
            for tpl in self.all_templates:
                self.tpl = tpl
                print(self.tpl)