Initial commit

main
Eric Ihli 6 months ago
commit 9b5e4c809e

2
.gitignore vendored

@ -0,0 +1,2 @@
.pyc
__pycache__

@ -0,0 +1,40 @@
import argparse
from typing import TypeVar, Generic, cast
Value = TypeVar("Value")
class Arg(Generic[Value]):
value: Value
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def __set_name__(self, owner, name):
owner.arguments.append(name)
def __get__(self, instance, owner) -> Value:
return self.value
class TypedNamespace(argparse.Namespace):
arguments = []
@property
def descriptors(self):
return [(arg, self.__class__.__dict__[arg]) for arg in self.arguments]
Namespace = TypeVar("Namespace", bound=argparse.Namespace)
class ParseArger(argparse.ArgumentParser, Generic[Namespace]):
def __init__(self, *args, namespace: Namespace, **kwargs):
super().__init__(*args, **kwargs)
self.namespace = namespace
if namespace is not None:
for name, descriptor in namespace.descriptors:
self.add_argument(f"--{name.replace('_', '-')}", *descriptor.args, **descriptor.kwargs)
def parse_args(self, args=None) -> Namespace:
return cast(Namespace, super().parse_args(args=args, namespace=self.namespace))

@ -0,0 +1,11 @@
from parsearger import ParseArger, Arg, TypedNamespace
class CliArgs(TypedNamespace):
num_things = Arg[int](help="Some help message", type=int)
name_thing = Arg[str](help="Name of some thing")
namespace = CliArgs()
parser = ParseArger(namespace=namespace)
args = parser.parse_args()
args.num_things
args.name_thing

@ -0,0 +1,16 @@
from collections import namedtuple
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--num-things", help="Number of things", type=int)
args.num_things
parser = argparse.ArgumentParser()
parser.add_argument('--some-arg')
parser.add_argument('--another-arg')
MagicNamespace = namedtuple('MagicNamespace', [act.dest for act in parser._actions])
mn = MagicNamespace()
mn.some_arg
mn.foo
parsed = parser.parse_args(['--some-arg', 'val1', '--another-arg', 'val2'], namespace=mn)
parsed.some_arg
parsed.foo
Loading…
Cancel
Save