Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid global variable in a python util file

Tags:

python

I have a utilities.py file for my python project. It contains only util functions, for example is_float(string), is_empty(file), etc.

Now I want to have a function is_valid(number), which has to:

  1. read from a file, valid.txt, which contains all numbers which are valid, and load them onto a map/set.
  2. check the map for the presence of number and return True or False.

This function is called often, and running time should be as small as possible. I don't want to read open and read valid.txt everytime the function is called. The only solution I have come up with is to use a global variable, valid_dict, which is loaded once from valid.txt when utilities.py is imported. The loading code is written as main in utilities.py.

My question is how do I do this without using a global variable, as it is considered bad practice? What is a good design pattern for doing such a task without using globals? Also note again that this is a util file, so there should ideally be no main as such, just functions.

like image 784
harishankarv Avatar asked Mar 12 '23 00:03

harishankarv


1 Answers

The following is a simple example of a closure. The dictionary, cache, is encapsulated within the outer function (load_func), but remains in scope of the inner, even when it is returned. Notice that load_func returns the inner function as an object, it does not call it.

In utilities.py:

def _load_func(filename):

    cache = {}

    with open(filename) as fn:
        for line in fn:
            key, value = line.split()
            cache[int(key)] = value

    def inner(number):
        return number in cache

    return inner

is_valid = _load_func('valid.txt')

In __main__:

from utilities import is_valid                  # or something similar

if is_valid(42):
    print(42, 'is valid')
else:
    print(42, 'is not valid')

The dictionary (cache) creation could have been done using a dictionary comprehension, but I wanted you to concentrate on the closure.

like image 71
cdarke Avatar answered Mar 25 '23 11:03

cdarke