Home > database >  Are class variables accessed via self used as iterables good practice/pythonic?
Are class variables accessed via self used as iterables good practice/pythonic?

Time:12-16

Is it appropriate to use a class variable accessed with self as an iterable in a loop? The following python code is valid and produces the expected result ("1, 2, 3") but it feels wrong somehow:

class myClass():
    foo = None
    def myfunc(self):
        for self.foo in [1, 2, 3]:
            print(self.foo)
        return

myClass().myfunc()

I have not found a definitive answer that suggests using self.foo would be considered good or bad programming.

CodePudding user response:

In general, it is not considered good practice to use a class variable accessed with self as an iterable in a loop, as it can lead to unexpected behavior and can make the code difficult to read and understand. In the code example you provided, using self.foo as an iterable in the for loop will overwrite the value of self.foo with each iteration of the loop, which can lead to confusion and make it difficult to access the original value of self.foo later in the code.

Instead, it is better to use a separate variable as the iterable in the for loop. For example, you could use a local variable declared within the myfunc method, like this:

class myClass():
    foo = None
    def myfunc(self):
        for item in [1, 2, 3]:
            self.foo = item
            print(self.foo)
        return

myClass().myfunc()

This way, the original value of self.foo is preserved, and the code is easier to read and understand.

It is also worth noting that in this particular example, it may be better to avoid using a class variable altogether, and simply use a local variable within the myfunc method. For example:

class myClass():
    def myfunc(self):
        foo = None
        for item in [1, 2, 3]:
            foo = item
            print(foo)
        return

myClass().myfunc()

This way, you avoid using self unnecessarily, and you avoid any potential confusion or unexpected behavior that can arise from using a class variable as an iterable in a for loop.

  • Related