0

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
  • 201,845
  • 13
  • 203
  • 313
wstcegg
  • 51
  • 5

1 Answers1

2

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,005
  • 5
  • 34
  • 42