Skip to content

Instantly share code, notes, and snippets.

@rec
Last active June 17, 2022 11:26
Show Gist options
  • Save rec/314411659fe447aaf8b0b0cba7390b90 to your computer and use it in GitHub Desktop.
Save rec/314411659fe447aaf8b0b0cba7390b90 to your computer and use it in GitHub Desktop.
# 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
@rec
Copy link
Author

rec commented Jun 17, 2022 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment