Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how to deep copy the Namespace obj "args" from argparse

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

like image 918
Hao Shen Avatar asked Sep 07 '16 18:09

Hao Shen


People also ask

How do you convert Argparse namespace to dictionary?

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.

How do you pass arguments to Argparse?

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.

What is namespace in Python Argparse?

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.


2 Answers

import copy
args = parser.parse_args()
args_copy = copy.deepcopy(args)

Tested with Python 2.7.15

like image 118
Kamaraju Kusumanchi Avatar answered Oct 19 '22 02:10

Kamaraju Kusumanchi


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
like image 27
Hao Shen Avatar answered Oct 19 '22 01:10

Hao Shen