[英]Python2.7 - Passing function list AND dictionary to the global namespace
TL; DR如何将两种类型的数据(例如字典和列表)从函数传递到全局命名空间中的字典和列表?
我正在编写一个与设备交互的脚本。 该脚本要求用户提供多个包含CSV的文本文件。 然后将这些值放在适当的列表和字典中。
因为文件将以相同的方式处理,所以我将处理代码放入一个函数中(本着DRY的精神)。 问题是无论函数运行多少次,我都希望将所有列表条目添加到单个列表中,所有字典条目添加到单个字典中,但是,我在此范围界定方面遇到了麻烦。
据我了解,函数驻留在本地名称空间中。 因此,我无法使函数将数据追加到全局名称空间的“主”列表和字典中(不使用“全局”变量,这当然是不可以)。
我知道我可以从函数中返回值以使数据在全局名称空间中可用,但是据我了解,我只能以一种形式(例如,元组,字典等)返回它们。如果是这种情况,它将不会也不能满足我的需求。
我的问题是,如何将两种类型的数据(例如字典和列表)从函数传递到全局命名空间中的字典和列表?
def func():
return [1,2], {'abc':5}
alist, dictionary = func()
print alist, dictionary
Output: [1,2] {'abc': 5}
print type(alist), type(dictionary)
Output: (type 'list') (type 'dict')
它不是不能拒绝的global
关键字,而是全局名称空间本身中的“主”列表和字典 。 问题是您降低了整体灵活性(如果其他一些代码想要导入模块并管理其自己的容器又如何),并使代码的管理性变得不那么明显(您需要跟踪触摸这些容器的所有位置) 。 这些是设计的折衷,可能在您的环境中可以合理接受。
因为这些是容器,并且您可以从函数中的模块全局名称空间读取变量(只是无法重新分配它们),所以可以在不使用global
关键字的情况下使用它们。 请注意,您仍在使用全局变量。
my_list = []
my_dict = {}
def func():
while True:
filename = input("Enter csv file, or 'done'")
if filename == 'done':
break
my_list.append(filename)
# not sure what to add to dict, but you get the point
def main():
# this adds to the global containers
func()
# but be careful, this adds to the global containers and skips these
# local versions
my_list = ['foo']
my_dict = {'bar':'baz'}
func() # doesn't change the local objects
您可以根据需要将容器传递给函数,从而将其与全局名称空间分离。
def func(my_list, my_dict):
while True:
filename = input("Enter csv file, or 'done'")
if filename == 'done':
break
my_list.append(filename)
# not sure what to add to dict, but you get the point
def main():
# this adds to the local containers
my_list = ['foo']
my_dict = {'bar':'baz'}
func(my_list, my_dict)
您也可以开始将这些容器捆绑到自己的类中。 这更多的是繁重的工作,因为您可能想将使用这些容器的更多功能也放到类中。
class MyContainers:
def __init__(self):
self.my_list = []
self.my_dict = {}
def func(self):
while True:
filename = input("Enter csv file, or 'done'")
if filename == 'done':
break
self.my_list.append(filename)
# not sure what to add to dict, but you get the point
def main():
foo = MyContainers()
foo.func()
print(foo.my_list)
print(foo.my_dict)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.