I got "args" from argparse:
args = parser.parse_args()
I want to pass it to two different functions with slight modifications each. That's why I want to deep copy the args, modify the copy and pass them to each function.
However, the copy.deepcopy just doesn't work. It gives me:
TypeError: cannot deepcopy this pattern object
So what's the right way to do it? Thanks
Use vars() to convert argparse. Namespace() entries into a dictionary. Call vars(args) with args as a argparse. Namespace() object to convert the key-value pairings in args into a dictionary.
First, we need the argparse package, so we go ahead and import it on Line 2. On Line 5 we instantiate the ArgumentParser object as ap . Then on Lines 6 and 7 we add our only argument, --name . We must specify both shorthand ( -n ) and longhand versions ( --name ) where either flag could be used in the command line.
Class argparse. Namespace is a simple class used for creating an object by parse_args() which holds the attributes and returns it. This class is a subclass of Object class with a very simple and readable string representation. We can get a dictionary-like structure of the attributes stored in it using vars() in Python.
import copy
args = parser.parse_args()
args_copy = copy.deepcopy(args)
Tested with Python 2.7.15
I myself just figured out a way to do it:
args_copy = Namespace(**vars(args))
Not real deep copy. But at least "deeper" than:
args_copy = args
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With