Python Class Attributes

As you know, sometimes programming is all about efficiency. The problem is when not typing "self" out of laziness takes an hour of debugging to find out.

Reading Time: ~2 min
card.jpg

Turns out I’m stupid. I’ve been using Python for years and somehow didn’t realize I was using Python’s class attributes in my NetBox Proxmox-Sync plugin.

It took me quite a few minutes to understand why the hell when I tried to sync the second cluster it would bring up information from the first one.

I basically found out (again) about Python’s Class Attributes the hard way.

The fix was just using the normal attributes, which was my intention to begin with.

Note

Don’t mind the extra “debugging” code with prints and ifs. I hadn’t set up a debugger for my neovim yet.

Which reminds me: I gotta update my dotfiles repo. Ideally with an “easy install option” or something.

Quick example of how they work:

class Whatever:
    # this is a "Class Attribute"
    something = []
    def __init__(self):
        pass

    def addThing(self, thing):
        self.something.append(thing)

    def showme(self):
        print(self.something)

w1 = Whatever()
w1.showme()  # outputs []
w1.addThing("1")
w1.addThing("2")
w1.addThing("3")
w1.showme()  # outputs ['1', '2', '3']

w2 = Whatever()
w2.showme() # outputs ['1', '2', '3']... wait what?

By all means, it makes absolute sense. Just like you define the methods in the top-level and they’re available in the class itself, so should the top-level attributes.

I honestly expected to need a “static” keyword to do this, like Java-ish languages.

Essentially a brain-fart that took a day to solve because I’ve never used the class attributes by accident before. Quite the experience.