sorted-attributes

Sort contiguous class assignment groups when the class docstring contains @sorted-attributes. Reordering assignments can change the order in which right-hand-side expressions run, so use this directive only for side-effect-free class attributes.

Message

Class assignments under @sorted-attributes are not sorted; sorting them can change right-hand-side side-effect order.

Valid examples

class MyConstants:
    """
    @sorted-attributes
    """
    A = 'zzz123'
    B = 'aaa234'

class MyUnsortedConstants:
    B = 'aaa234'
    A = 'zzz123'
Show more
class MyConstants:
    """
    @sorted-attributes
    """
    z = side_effect("z")

    def method(self):
        pass

    a = side_effect("a")

Invalid examples

class MyUnsortedConstants:
    """
    @sorted-attributes
    """
    z = "hehehe"
    B = 'aaa234'
    A = 'zzz123'
    cab = "foo bar"
    Daaa = "banana"

    @classmethod
    def get_foo(cls) -> str:
        return "some random thing"

Suggested fix

class MyUnsortedConstants:
    """
    @sorted-attributes
    """
    A = 'zzz123'
    B = 'aaa234'
    Daaa = "banana"
    cab = "foo bar"
    z = "hehehe"

    @classmethod
    def get_foo(cls) -> str:
        return "some random thing"
Show more
class MyUnsortedConstants:
    """
    @sorted-attributes
    """
    z: int = 1
    a: int = 2

Suggested fix

class MyUnsortedConstants:
    """
    @sorted-attributes
    """
    a: int = 2
    z: int = 1