Suppose i have a list of reference numbers in a file numbers.csv
.
I am writing a module checker.py
that can be imported and called to check for numbers like this:
import checker
checker.check_number(1234)
checker.py
will load a list of numbers and provide check_number
to check if a given number is in the list. By default it should load the data from numbers.csv
, although the path can be specified:
DATA_FILEPATH = 'numbers.csv'
def load_data(data_filepath=DATA_FILEPATH):
...
REF_LIST = load_data()
def check_number(num, ref_list=REF_LIST):
...
Question -- Interleaving variables and functions seems strange to me. Is there a better way to structure checker.py
than the above?
I read the excellent answer to How to create module-wide variables in Python?.
Is the best practice to:
declare
REF_LIST
list i have done above?create a dict like
VARS = {'REF_LIST': None}
and setVARS['REF_LIST']
inload_data
?create a trivial class and assign
clas.REF_LIST
inload_data
?or else, is it dependent on the situation? (And in what situations do i use which?)
Note
Previously, i avoided this by loading the data only when needed in the calling module. So in checker.py
:
DATA_FILEPATH = 'numbers.csv'
def load_data(data_filepath=DATA_FILEPATH):
...
def check_number(num, ref_list):
...
In the calling module:
import checker
ref_list = checker.load_data()
checker.check_number(1234, ref_list)
But it didn't quite make sense for me to load in the calling module, because i would need to load_data
5 times if i want to check numbers in 5 different modules.