Created
March 21, 2019 20:02
-
-
Save dmitriy-serdyuk/bd434258e90697bafc5969a06083af73 to your computer and use it in GitHub Desktop.
Arparse meets dataclasses: automatically create parser for a given dataclass
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
import argparse | |
import dataclasses | |
__all__ = ('Arg', 'Int', 'Float', 'Str', 'Choice', 'parse_to') | |
class Arg: | |
def __init__(self, **kwargs): | |
super().__init__() | |
self.kwargs = kwargs | |
class Int(Arg): | |
def __init__(self, **kwargs): | |
super().__init__(type=int, **kwargs) | |
class Float(Arg): | |
def __init__(self, **kwargs): | |
super().__init__(type=float, **kwargs) | |
class Str(Arg): | |
def __init__(self, **kwargs): | |
super().__init__(type=str, **kwargs) | |
class _MetaChoice(type): | |
def __getitem__(self, item): | |
return self(choices=list(item), type=item) | |
class Choice(Arg, metaclass=_MetaChoice): | |
def __init__(self, choices, **kwargs): | |
super().__init__(choices=choices, **kwargs) | |
def parse_to(container_class, **kwargs): | |
def mangle_name(name): | |
return '--' + name.replace('_', '-') | |
parser = argparse.ArgumentParser( | |
description=container_class.__doc__) | |
for field in dataclasses.fields(container_class): | |
name = field.name | |
default = field.default | |
value_or_class = field.type | |
if isinstance(value_or_class, type): | |
value = value_or_class(default=default) | |
else: | |
value = value_or_class | |
value.kwargs['default'] = default | |
parser.add_argument( | |
mangle_name(name), **value.kwargs) | |
arg_dict = parser.parse_args(**kwargs) | |
return container_class(**vars(arg_dict)) |
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
import arg | |
import torch | |
from dataclasses import dataclass | |
from enum import Enum | |
class Action(Enum): | |
TRAIN = 'train' | |
TEST = 'test' | |
class Datasets(Enum): | |
MNIST = 'mnist' | |
CIFAR = 'cifar' | |
class Nets(Enum): | |
CNN = 'cnn' | |
RESNET = 'resnet' | |
@dataclass(frozen=True) | |
class Args: | |
"""My new cool model""" | |
action: arg.Choice[Action] | |
n_batches: arg.Int(help="Nubmer of batches") = 100 | |
save_epoch: arg.Int = 20 | |
device: arg.Arg(type=torch.device) = torch.device('cpu') | |
dataset: arg.Choice[Datasets] = Datasets.MNIST | |
model: arg.Choice[Nets] = Nets.CNN | |
num_workers: arg.Int = 8 | |
seed: arg.Int = 123 | |
lr: arg.Float = 0.001 | |
arg.parse_to(Args, args=['--help']) | |
# prints | |
""" | |
usage: ipython [-h] [--action {Action.TRAIN,Action.TEST}] | |
[--n-batches N_BATCHES] [--save-epoch SAVE_EPOCH] | |
[--device DEVICE] [--dataset {Datasets.MNIST,Datasets.CIFAR}] | |
[--model {Nets.CNN,Nets.RESNET}] [--num-workers NUM_WORKERS] | |
[--seed SEED] [--lr LR] | |
My new cool model | |
optional arguments: | |
-h, --help show this help message and exit | |
--action {Action.TRAIN,Action.TEST} | |
--n-batches N_BATCHES | |
Nubmer of batches | |
--save-epoch SAVE_EPOCH | |
--device DEVICE | |
--dataset {Datasets.MNIST,Datasets.CIFAR} | |
--model {Nets.CNN,Nets.RESNET} | |
--num-workers NUM_WORKERS | |
--seed SEED | |
--lr LR | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sure. Here: