繁体   English   中英

访问变量时,python 可以“按需”从文件加载数据吗?

[英]Can python load data from a file "on demand" when a variable is accessed?

我正在使用 python 3.6 并且我有很长的 ID 号列表,我想将它们缓存在文件中,但仅在需要时才将它们加载到内存中。 理想情况下,我希望它们显示为在访问时从文件加载的列表类型变量,如下所示。

""" contents of a library file, canned_lists.py """
list_of_ids = []
def event_driven_on_access_of_list_of_ids():
    # don't allow access to the empty list yet
    global list_of_ids
    with open("the_id_file.csv", "r") as f:
        list_of_ids = f.readlines()
    # now the list is ready, it can be accessed
""" contents of a calling file, script.py """
import canned_lists
for id in canned_lists.list_of_ids:  # at this point, list_of_ids should populate from a file
    print("do something with the ids")

替代选项 A 是使用函数而不是变量。 这有效并且确实不错,但从美学角度来看,我想导入一个列表并使用一个列表而不是一个函数。

""" contents of a library file, canned_lists.py """
def get_list_of_ids():
    with open("the_file.csv", "r") as f:
        return f.readlines()

替代选项 B 将仅将数据存储在代码中。 列表可能有近 20,000 个 ID,因此选项 B 笨拙且难以管理。 它还会导致 PyCharm 告诉我我的文件大小超出了 Code Insight 功能的配置限制。 我可能会增加限制,但将数据移出代码似乎更合理。

""" contents of a library file, canned_lists.py """
list_of_ids = [123, 124, 125, 126, ]

python 是否有办法支持更改“访问时”变量以支持顶部选项? 或者有人有更好的主意吗? 我可能会实现替代方案 A,因为它功能完善,但我渴望向更高级的 pythonistas 学习。

您可以在类的上下文中使用属性,这会导致在访问变量时调用函数:

class X:
    @property
    def thing(self):
        return 42

print(X().thing) # prints 42, note no function call syntax

需要注意的两件事:(1)每个属性访问都会调用该函数,因此您可能希望将结果缓存在类中以提高性能; (2) 通常期望属性访问是快速的,也就是说,您的代码的用户不会期望属性访问执行缓慢的文件操作(这将违反最小意外原则)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM