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 | |
""" |
Sure. Here:
Copyright (c) 2021 Dmitriy Serdyuk
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey Dmitriy, thanks for sharing these code snippets.
I wanted to ask if you could provide a license for the code above because I would like to use your approach for parsing arguments in the code of my thesis.