Say I have several variables or objects in Python, a
, b
, c
, ...
How can I easly dump these variables into a namespace in Python and restore them at a later time? (e.g. in the same way argparse
wraps various variables into a namespace).
Here are two examples of how I would like to dump things to and from a namespace:
Dumping local variables into a namespace
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
Dumping local variables from a namespace 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
My first question is: Is this possible at all in Python? (note that the method dump_into_namespace
does not directly receive the names of the variables, at least as far as I can tell).
If the answer to the above is no, how could I do it with an interface like this?
e = dump_into_namespace('a', 'b', 'c')
Also, how would this be done this with a dictionary instead of a namespace?
There are a few threads that seem relevant addressing a dot-access of dynamically-defined variables, but I don't think they address the problem of dumping variables:
See also
- 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?
Are there any libraries that facilitate this type of access through dot notation?
Update:
It looks like there is a library that supports dot-accessible dictionaries in Python, called Bunch, but I am not sure it would support easily dumping as I defined it.