Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading