Create namedtuple from Namspace?

How to initialize namedtuple

from 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 if only a few script arguments come in namedtuple?

This 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?

+3


source to share


1 answer


If you don't want an actual namedtuple type, you can create an "anonymous" namedtuple to represent yours Namespace

.

This is the approach I used before:

def auto_namedtuple(classname='auto_namedtuple', **kwargs):
    return collections.namedtuple(classname, tuple(kwargs))(**kwargs)

      



Usage in your case:

nt = auto_namedtuple(**vars(args))

      

0


source







All Articles