Last active
June 17, 2022 11:26
-
-
Save rec/314411659fe447aaf8b0b0cba7390b90 to your computer and use it in GitHub Desktop.
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
# 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 |
Thanks for catching this!
I fixed the gist to be self-contained - but actually, I have released this
code as a module with full unit tests and a little additional functionality
(the ability to make the original typer function callable like a function).
https://pypi.org/project/dtyper/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 35 uses 'datacls', which isn't defined.
EDIT: it seems to be this... https://github.com/rec/datacls so this is not self contained.