Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

attrs/dataclasses-style decorator helper #324

Open
kurtbrose opened this issue Jan 25, 2023 · 0 comments
Open

attrs/dataclasses-style decorator helper #324

kurtbrose opened this issue Jan 25, 2023 · 0 comments

Comments

@kurtbrose
Copy link
Contributor

There's probably a better name for this, but the idea is to write decorator + kwargs -- so you don't have to do @decorator() if there aren't any arguments being passed.

def maybe_arg_decorator(callable):
  """
  There's this fun trick that dataclasses.dataclass decorator does,
  where you can use it both directly as a decorator, or call it with kwargs and use
  that as the decorator.

  This helper converts a function with 1 positional argument and a bunch of kwargs
  into one of those.


  @maybe_arg_decorator
  def simple_decorator(decorated, a=1, b=2):
     pass

  @simple_decorator
  def thing(): pass

  @simple_decorator(a=3)
  def other_thing(): pass
  """
  @wraps(callable)
  def wrapper(decorated=None, /, **kwargs):
    if decorated:
      return callable(decorated)

    def double_wrapper(decorated, /):
      return callable(decorated, **kwargs)

    return double_wrapper

  return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant