Navonod Navonod - 1 year ago 63
Python Question

Variable behaviour in python - making more efficient code

Trying to do some optimization here on a class. We're trying not to change too much the class definitions. In essence we are instantiating a

times but one of the methods has a nasty file read.

for x in range(0, N):
cl = ClassA()

The class looks like this:

class ClassA:
def dostuff(self, x):
#open nasty file here
nastyfile = open()
do something else

We could bring that file read out of the class and put in before the loop as the file will not change. But is there a way we can ensure that we only ever open the nasty file once for instances of the class. I.e. so for example on the first instantiate of the class it is defined for all future instances of the class without having to read in again. Is there a way to do this in the current form without really changing the structure too much of the existing code base.

One question relates to the interpreter - i.e. is python smart enough to cache variables just as nastyfile, so that we do as we are, or is the quick and dirty solution the following:

nastyfile = open()
for x in range(0, 1):
cl = ClassA()

Looking for a pythonic way to do this.

Answer Source

You could encapsulate opening the file in a classmethod.

class ClassA():

    def open_nasty_file(cls):
        cls.nasty_file = open('file_path', 'file_mode')

    def do_stuff(self):
        if not hasattr(self, 'nasty_file'):

This approach relies on the fact that attribute look-ups will try finding the attribute on the class if not found on the instance.

You could put this check/instantiation in the __init__ function if you want it opened when the first instance is instantiated.

Note that this method will leave the file open, so it will need to be closed at some point.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download