Create namedtuple from Namspace?

Viewed 650

How do I initialize a namedtuple from a Namespace?

import collections
import argparse

nt=collections.namedtuple("nt",["foo","bar"]) # _NOT_ "baz"!
parser = argparse.ArgumentParser()
parser.add_argument('--foo')
parser.add_argument('--bar')
parser.add_argument('--baz')
args = parser.parse_args(...)

What do I do if only some script arguments go into the namedtuple?

Here is what I came up with:

nt_param=nt(**{f:getattr(args,f,None) for f in nt._fields})

is there a more pythonic approach?

1 Answers
Related