Issue
I want to merge 2 argparse.Namespace
objects in Python 2.x.
In python 3.x I can do something like this:
from argparse import Namespace
# The 2 initial objects
options_foo = Namespace(foo="foo")
options_bar = Namespace(bar="bar")
# the merged object
options_baz = Namespace(**vars(options_foo), **vars(options_bar))
And get:
print(options_baz)
# Namespace(foo="foo", bar="bar")
But in python 2.x I can't. I get the following error.
SyntaxError: invalid syntax
Is there an easy way to achieve this?
Solution
I've majorly reconsidered this answer, because I didn't fully read and understand your problem...
It's true that this line is valid in Python3, and invalid in Python2:
options_baz = Namespace(**vars(options_foo), **vars(options_bar))
When we look at the error, we see that it's the comma (,
) that Python2 cannot accept:
File "main.py", line 8
options_baz = Namespace(**vars(options_foo), **vars(options_bar))
^
SyntaxError: invalid syntax
So, let's just avoid passing two sets of options to the Namespace()
initializer:
...
dict_baz = vars(options_foo)
dict_baz.update(vars(options_bar))
# the merged object
options_baz = Namespace(**dict_baz)
print(options_baz)
and we get:
Namespace(bar='bar', foo='foo')
In another answer you pointed out that the double-star (**
) syntax is invalid, but that's definitely valid syntax. We can see it mentioned as far back as Python 2.2:
If the syntax
**expression
appears in the function call,expression
must evaluate to a (subclass of) dictionary, ...
It was just that comma all along.
Answered By - Zach Young
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.