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

3

14

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

Pegmatite answered 7/9, 2016 at 18:21 Comment(3)
copy.deepcopy seems to work fine on an empty argparse.Namespace in python 2.7.10 (and 3.6.0a2) ... Are you sure it's the Namespace that is an issue and not the contents of the namespace?Indiscrimination
@Indiscrimination You are right. It's the issue of the contents of the namespace. I just do not know what's the best way to handle this situation as the simple deepcopy doesn't work.Pegmatite
We can't help you if we know nothing about the contents.Frontal
P
10

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
Pegmatite answered 7/9, 2016 at 20:40 Comment(5)
That's a shallow copy.Sheerness
You probably didn't know what to try to properly test whether the copy was deep. It's definitely shallow.Sheerness
@Sheerness You are right~ What made me thought it was deep is that I did some "not in-place" change of the args_copy attribute which seems to create another copy of that attribute.Pegmatite
@Sheerness But at least it turns out to be "deeper" than args_copy=args :)Pegmatite
Yeah, args_copy=args is called things like "reference copy" or "not even a copy".Sheerness
V
6
import copy
args = parser.parse_args()
args_copy = copy.deepcopy(args)

Tested with Python 2.7.15

Vannavannatta answered 9/10, 2018 at 15:49 Comment(1)
This will definitely not produce a deep copy, a list attribute will not be duplicated.Incipit
S
0

This might be a solution for you using deepcopy

import argparse
import copy
 
a = argparse.Namespace(x=[1])
b = argparse.Namespace(**vars(a))
c = argparse.Namespace(**{k: copy.deepcopy(v) for k, v in vars(a).items()})
 
# b is wrong
b.x.append(2)
print(a.x)
 
# c makes deepcopy
a.x.append(3)
print(c.x)  # should only print out [1]

https://ideone.com/HCHaAL

Sandler answered 28/5, 2024 at 9:37 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.