[英]Python: Best way to structure module variables in imported module
Suppose i have a list of reference numbers in a file numbers.csv
. 假设我在numbers.csv
文件中有一个参考编号列表。
I am writing a module checker.py
that can be imported and called to check for numbers like this: 我正在编写一个模块checker.py
,可以将其导入并调用以检查像这样的数字:
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. checker.py
将加载一个数字列表,并提供check_number
来检查列表中是否有给定的数字。 By default it should load the data from numbers.csv
, although the path can be specified: 默认情况下,它应该从numbers.csv
加载数据,尽管可以指定路径:
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? 有没有比上述更好的方法来构造checker.py
?
I read the excellent answer to How to create module-wide variables in Python? 我阅读了有关如何在Python中创建模块范围的变量的出色答案? . 。
Is the best practice to: 最佳做法是:
declare REF_LIST
list i have done above? 声明我在上面完成的REF_LIST
列表?
create a dict like VARS = {'REF_LIST': None}
and set VARS['REF_LIST']
in load_data
? 创建一个类似VARS = {'REF_LIST': None}
的字典,并在load_data
设置VARS['REF_LIST']
?
create a trivial class and assign clas.REF_LIST
in load_data
? 创建一个普通的类,并分配clas.REF_LIST
在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
: 因此在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. 但这对我来说加载到调用模块中并不是很有意义,因为如果我想检查5个不同模块中的数字,则需要将load_data
5次。
You can load csv data easily with help of Pandas framework 您可以借助Pandas框架轻松加载csv数据
import pandas as pd
dataframe=pd.read_csv('numbers.csv')
to check a number is present in the datframe by using this code: 使用以下代码检查datframe中是否存在数字:
numbers=[1,3,8]
for number in numbers:
if number in dataframe[dataframe.columns[0]]:
print True
else:
print False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.