namespaces
Namespaces Utility Functions for Declarative Typed Argument Parsing.
The namespaces
module contains a utility function used for recursively
converting argparse.Namespace
s to regular Python dict
s.
to_dict(namespace)
Converts a nested namespace to a dictionary recursively.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
namespace |
argparse.Namespace |
Namespace object to convert. |
required |
Returns:
Type | Description |
---|---|
Dict[str, Any] |
Nested dictionary generated from namespace. |
Source code in pydantic_argparse/utils/namespaces.py
def to_dict(namespace: argparse.Namespace) -> Dict[str, Any]:
"""Converts a nested namespace to a dictionary recursively.
Args:
namespace (argparse.Namespace): Namespace object to convert.
Returns:
Dict[str, Any]: Nested dictionary generated from namespace.
"""
# Get Dictionary from Namespace Vars
dictionary = vars(namespace)
# Loop Through Dictionary
for key, value in dictionary.items():
# Check for Namespace Objects
if isinstance(value, argparse.Namespace):
# Recurse
dictionary[key] = to_dict(value)
# Return
return dictionary