Python: unexpected behavior with static initializer

I’ve been working on an IOT project using a Raspberry PI Zero W. I fully intend to document it here in a future post, so I won’t go into details about it now.

This post came about because I was troubleshooting a problem and the root cause surprised me.

I come from the world of C#/Java/Swift and part of the reason for taking on this project was learning a new language. The code for this device is written in Python.

Python has OOP structures like the aforementioned languages and I expected similar behavior. The OOP mantra, of course is, Encapsulation, Inheritance, Polymorphism.

From my reading it seems that Python doesn’t have the same idea of private/public as other languages making the first principle a bit fuzzy.

I have a class with quite a few class variables. This class is instantiated multiple times and I fully expected that the variables from each instantiation would be distinct. However, in this case, one of them was not.

I have code that looks like this:

class myClass:
    myData = [0] * 100

Later I fill the array with data.

What I discovered was that apparently all of the arrays were mapped to the same address space. I only had one copy of the data and was overwriting it in each class instance. As I was expecting each to be unique, this was not the desired behavior.

The solution was simple, I moved the initialization into the class __init:

def __init(self, vars...):
    self.myData = [0] * 100

It now works as expected, but it took quite a while to drill down to the root cause.

StackOverflow question here.

Leave a Reply

Your email address will not be published. Required fields are marked *