0

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 set VARS['REF_LIST'] in load_data?

  • create a trivial class and assign clas.REF_LIST in load_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.

iamanigeeit
  • 654
  • 4
  • 11

1 Answers1

0

You can load csv data easily with help of Pandas framework

import pandas as pd
dataframe=pd.read_csv('numbers.csv')

to check a number is present in the datframe by using this code:

numbers=[1,3,8]
for number in numbers:
    if number in dataframe[dataframe.columns[0]]:
        print True
    else:
        print False
vishalk
  • 152
  • 1
  • 10
  • Sorry, maybe i'm not being clear enough. I'm not looking for a way to load data from Pandas or check numbers -- it's just an example. Will edit the question to reflect the real issue. – iamanigeeit Aug 30 '18 at 05:25