Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #32 from speg03/feature/use-any-delimiter-for-name…
…space Use a different delimiter for namespace
- Loading branch information
Showing
3 changed files
with
54 additions
and
18 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,27 +1,36 @@ | ||
import argparse | ||
|
||
DEFAULT_DELIMITER = "." # default delimiter for nested namespaces | ||
|
||
class NestedNamespace(argparse.Namespace): | ||
DELIMITER = "." | ||
|
||
def __setattr__(self, name, value): | ||
try: | ||
parent, name = name.split(self.DELIMITER, maxsplit=1) | ||
except ValueError: | ||
parent = None | ||
def create_namespace(delimiter: str): | ||
class _NestedNamespace(argparse.Namespace): | ||
def __setattr__(self, name, value): | ||
if delimiter in name: | ||
parent, name = name.split(delimiter, maxsplit=1) | ||
else: | ||
parent = None | ||
|
||
if parent: | ||
if not hasattr(self, parent): | ||
super().__setattr__(parent, NestedNamespace()) | ||
setattr(getattr(self, parent), name, value) | ||
elif parent is not None: | ||
raise ValueError("parent should not be empty: {}".format(name)) | ||
else: | ||
super().__setattr__(name, value) | ||
if parent: | ||
if not hasattr(self, parent): | ||
super().__setattr__(parent, self.__class__()) | ||
setattr(getattr(self, parent), name, value) | ||
elif parent is not None: | ||
raise ValueError("parent should not be empty: {}".format(name)) | ||
else: | ||
super().__setattr__(name, value) | ||
|
||
return _NestedNamespace() | ||
|
||
|
||
class NestedArgumentParser(argparse.ArgumentParser): | ||
"""ArgumentParser that supports nested namespaces.""" | ||
|
||
def __init__(self, delimiter: str = DEFAULT_DELIMITER, **kwargs): | ||
self.delimiter = delimiter | ||
super().__init__(**kwargs) | ||
|
||
def parse_known_args(self, args=None, namespace=None): | ||
if namespace is None: | ||
namespace = NestedNamespace() | ||
namespace = create_namespace(self.delimiter) | ||
return super().parse_known_args(args=args, namespace=namespace) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters