wstcegg
wstcegg

Reputation: 171

Convert argparse Namespace to dict recursively

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.

Upvotes: 3

Views: 3086

Answers (1)

Francisco
Francisco

Reputation: 11486

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'}}

Upvotes: 4

Related Questions