Last active
June 17, 2022 11:26
-
-
Save rec/314411659fe447aaf8b0b0cba7390b90 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 has been replaced by the PyPi module https://pypi.org/project/dtyper/ | |
| from argparse import Namespace | |
| import dataclasses | |
| import functools | |
| import inspect | |
| @functools.wraps(dataclasses.make_dataclass) | |
| def dcommand(typer_f, **kwargs): | |
| required = True | |
| def field_desc(name, param): | |
| nonlocal required | |
| t = param.annotation or 'typing.Any' | |
| if param.default.default is not ...: | |
| required = False | |
| return name, t, dataclasses.field(default=param.default.default) | |
| if not required: | |
| raise ValueError('Required value after optional') | |
| return name, t | |
| kwargs.setdefault('cls_name', typer_f.__name__) | |
| params = inspect.signature(typer_f).parameters | |
| kwargs['fields'] = [field_desc(k, v) for k, v in params.items()] | |
| @functools.wraps(typer_f) | |
| def dcommand_decorator(function_or_class): | |
| assert callable(function_or_class) | |
| ka = dict(kwargs) | |
| ns = Namespace(**(ka.pop('namespace', None) or {})) | |
| if isinstance(function_or_class, type): | |
| ka['bases'] = *ka.get('bases', ()), function_or_class | |
| else: | |
| ns.__call__ = function_or_class | |
| ka['namespace'] = vars(ns) | |
| return dataclasses.make_dataclass(**ka) | |
| return dcommand_decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.