问题
This is really a few questions:
Is there a reason argparse uses a namespace instead of a dictionary?
Assuming I have a class with
__init__(self, init_method, *args). Theinit_methodparameter tells the init_function which way I want to initialize the class, whileargparameter gives all the arguments neccesary for the init. The arguments may be different for different methods. Should I use a dictionary, or a namespace?Assuming that I use a namespace, how do I pass the namespace to
__init__()?
回答1:
The designers of
arparseapparently felt it would be more convenient to access arguments asargs.arg_namerather than
args["arg_name"]This might be a matter of taste, though. I would have happily gone with the dictionary, especially given the fact that there is no
Namespaceclass in the standard library, except for the one inargparse.Use a dictionary.
If you really want a namespace here, you can use
init_function(**args.__dict__)…but I don't recommend it.
回答2:
It is easy to convert a Namespace into a dictionary using vars():
>>> vars(args)
来源:https://stackoverflow.com/questions/7968697/namespace-argparse-and-usage