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

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?

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 :

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.

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