可在当前名称空间中转储的Picklable数据容器 [英] Picklable data containers that are dumpable in the current namespace

查看:64
本文介绍了可在当前名称空间中转储的Picklable数据容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档建议以下机制在Python中动态创建数据容器:

The documentation suggests the following mechanism to dynamically create data containers in Python:

class Employee:
    pass

john = Employee() # Create an empty employee record

# Fill the fields of the record
john.name = 'John Doe'
john.dept = 'computer lab'
john.salary = 1000

以上内容使我们可以轻松地在一个标识符(john)内对一组变量进行分组,而不必像使用字典那样键入引号('').

The above allows one to easily group a diverse set of variables within one single identifier (john), without having to type quotes ('') as one would do with a dictionary.

我正在寻找一种解决方案,该解决方案允许我将各个部分(属性)转储"到当前名称空间中.我想到了三个想法/问题来解决这个问题:

I am looking for a solution that allows me to "dump" the pieces (the attributes) back into the current namespace. There are three ideas/problems that come to mind to address this:

1..给定john上方的标识符,如何以编程方式获取其属性列表?

1. Given the identifier above john, how can I programatically get a list of it's attributes?

2..如何轻松地在当前名称空间中dump john的属性? (即通过浅拷贝或深拷贝创建名为namedeptsalary的局部变量)

2. How can I easily dump john's attributes in the current namespace? (i.e. create local variables called name, dept, salary either via shallow or deep copies)

3..以下主题中的最高答案描述了一种从argparse创建的命名空间中转储变量的方法:

3. The top answer in the following thread describes a way to dump variables from the namespace created by argparse: Importing variables from a namespace object in Python

也许像上面的文章所述,我可以使用Namespace对象作为数据容器,然后使用以下命令轻松转储这些变量:

Perhaps I could use a Namespace object as a data container, as in the above post, and then easily dump those variables with:

locals().update(vars(john))

?

为方便起见,在下面,我提供了一个线程列表,其中讨论了在Python中创建数据容器的其他方法,其中一些方法似乎是不可选的:

For convenience, below I include a list of threads discussing other approaches for creating data containers in Python, some of which don't seem to be pickable:

  • Using Python class as a data container
  • Accessing dict keys like an attribute in Python?
  • Are there any 'gotchas' with this Python pattern?

作为参考,MATLAB通过saveload以及变量

For reference, MATLAB provides this exact functionality through save and load, and variables can be nested and unnested easily, eliminating the need for quotes/dictionaries for this purpose). The motivation behind this question is to identify mechanisms that support such "pickable workspaces" in Python.

推荐答案

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆