【发布时间】:2013-01-31 22:50:45
【问题描述】:
假设我在 Python 中有几个变量或对象,a,b,c,...
我怎样才能轻松地将这些变量转储到 Python 中的命名空间并在以后恢复它们? (例如,argparse 以同样的方式将各种变量包装到命名空间中)。
以下是我希望如何将内容转储到命名空间和从命名空间转储的两个示例:
将局部变量转储到命名空间中
function (bar):
# We start with a, b and c
a = 10
b = 20
c = "hello world"
# We can dump anything we want into e, by just passing things as arguments:
e = dump_into_namespace(a, b, c)
del a, b, c
print (e.a + e.b) # Prints 30
return e # We can return e if we want. This is just a use case scenario
从命名空间 e 转储局部变量
# We start with e, which for example was built with a call to
# dump_into_namespace(a,b,c) somewhere else in the program,
# in which case e would hold a, b and c
# We may receive e through a function call or load it from disk, e.g.:
function foo(e):
# The following call creates the variables a,b and c
# or updates their values if the already exist in memory
dump_from_namespace(e)
del e
print(a + b) # Prints 30
print(c) # Prints hello world
我的第一个问题是:这在 Python 中可能吗?(请注意,方法 dump_into_namespace 不直接接收变量的名称,至少据我所知) .
如果上面的答案是否定的,我怎么能用这样的界面来做呢?
e = dump_into_namespace('a', 'b', 'c')
另外,如何使用 dictionary 而不是 namespace 来做到这一点?
有一些线程似乎与解决动态定义变量的点访问相关,但我认为它们不能解决转储变量的问题:
另见
- Python: Extract variables out of namespace
- Picklable data containers that are dumpable in the current namespace
- Recursive DotDict
- How to use a dot "." to access members of dictionary?
- Javascript style dot notation for dictionary keys unpythonic?
- Accessing dict keys like an attribute?
- Recursively access dict via attributes as well as index access?
- Python: Easily access deeply nested dict (get and set)
- Are there any 'gotchas' with this Python pattern?
是否有任何库可以通过点符号来促进这种类型的访问?
更新:
看起来在 Python 中有一个支持点可访问字典的库,名为 Bunch,但我不确定它是否支持我定义的轻松转储。
【问题讨论】:
-
我对您的问题的解决方案和含义进行了很多思考。我有一个答案要写,但我的时间目前很忙。 - 第二种情况比第一种更容易。顺便说一句,它不能称为“从命名空间转储局部变量”,而是“将另一个命名空间的项目加载到本地命名空间”。我使用术语“项目”,因为它是唯一适合名称空间中成对元素(标识符、对象)的元素。
-
顺便说一句,你必须停止使用在 Python 中非常令人困惑的“变量”这个词,因为读者永远不知道在作者的心目中它是指一个标识符,还是一个 Python对象,或者这个词的纯粹意义上的变量('内容可以改变的内存块')。第三种可能是 Python 中的异端,因为 Python 中的一切都是对象,而 Python 对象不充当纯变量。
-
“将另一个命名空间的项目加载到本地命名空间”很容易,它包括像更新字典一样更新调用命名空间。但是有一个模棱两可的地方。 namespace 这个词可以指定一个真正的命名空间,就像全局和本地命名空间一样。或者 namespace 可以指定一个对象的所谓命名空间(“在某种意义上,一个对象的属性集也形成了一个命名空间。”docs.python.org/2/tutorial/classes.html)
-
不管怎样,不管是哪种情况,因为在这两种情况下,更新都包括更新字典。对于全局命名空间,它是
global()['blah'] = obj_1。对于本地命名空间,据我所知,是不可能更新的。对于对象的命名空间,它是objo.__dict__.update(loaded_namespace)。最后一种更新的细节取决于加载另一个命名空间内容的对象。对于作为对象的模块,另请查看执行特殊操作的函数__import__,但我不知道它的确切作用。
标签: python dictionary syntax nested