Avoid global variable in python utility file

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

Now I want to have a function is_valid(number)that should:

  • read from a file valid.txtthat contains all valid numbers and load them onto a card / set.
  • check the card for availability numberand return True or False.

This function is called frequently, and the runtime should be as short as possible. I do not want to read openly and read valid.txtevery time a function is called. The only solution I came across is to use a global variable valid_dictthat loads once from valid.txtwhen it is imported utilities.py. The download code is recorded as the main one in utilities.py.

My question is: how do I do this without using a global variable, as this is considered bad practice? What is a good design pattern to accomplish such a task without using global variables? Also note that this is a utility file, so ideally there should not be a main goal, just a function.

+4
source share
2 answers

. cache (load_func), , . , load_func , .

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')

__main__:

from utilities import is_valid                  # or something similar

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

(cache) , , .

+4

valid_dict , - utilities.py. , - from utilities import *. , .

, : valid_dict={} is_valid(). , dict, valid_dict.

def is_valid(number, valid_dict={}):
    if not valid_dict:
        # first call to is_valid: load valid.txt into valid_dict
    # do your check

valid_dict if -clause, : , valid_dict[x] = y - valid_dict.update(z).

(PS: , "" "".)

+3

All Articles