2

we already have some non-recursive solutions here.

import argparse
args = argparse.Namespace()
args.foo = 1
args.bar = [1,2,3]
args.c = argparse.Namespace()
args.c.foo = 'a'

d = vars(args)


>>> d
{'foo': 1, 'bar': [1, 2, 3], 'c': Namespace(foo='a')}

The problem is if a second-level entry is also a Namespace, what we actually get is a dict of Namespace.

The question is if there is a handy recursive solution that is ready for us.

hpaulj
  • 221,503
  • 14
  • 230
  • 353
wstcegg
  • 141
  • 1
  • 9

1 Answers1

4

I don't think there's an already-made recursive solution, but here's a simple one:

def namespace_to_dict(namespace):
    return {
        k: namespace_to_dict(v) if isinstance(v, argparse.Namespace) else v
        for k, v in vars(namespace).items()
    }

>>> namespace_to_dict(args)
{'foo': 1, 'bar': [1, 2, 3], 'c': {'foo': 'a'}}
Francisco
  • 10,918
  • 6
  • 34
  • 45