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
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. Given the identifier above john
, how can I programatically get a list of it's attributes?
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. 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
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))
?
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:
Connection with MATLAB workflows:
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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…