Is it bad to put expensive statements in static class attributes if class is instantiated often?

I have a class with the following structure.

class MyClass:
    my_variable = pickle.load(open("my_file.p", "rb"))

    def __init__(self):

I assume, pickle.load() is an expensive operation that is why I am wondering if it will get called every time I instantiate the class, or is it just once when the file is imported?

>Solution :

All class attributes (my_variable, __init__, etc) are defined when the class is defined. Methods like __init__ are called when the class is instantiated, but none of the class attributes are redefined at that point.

pickle.load will only be called once, when MyClass is first defined.

Basically, you can think of the class statement as being a declarative way of writing

def my_class_init(self):

namespace = {
    '__init__': my_class_init,
    'my_variable': pickle.load(...)

MyClass = type('MyClass', (), namespace)

with pickle.load only being called to define the dict bound to namespace.

Leave a Reply