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

Suggestion: Allow text to change when using decorate pattern. #157

Open
liudonghua123 opened this issue Mar 24, 2021 · 1 comment
Open

Comments

@liudonghua123
Copy link

Description

I like the decorate pattern, but I found the text is always constant. I hope the text could change using some format strings.

I also write a simple version, it seems work as expected. Maybe the exist Halo.__call__ could be refactor.

from halo import Halo
from time import sleep

from functools import wraps
class HaloExtend:
  def __init__(self, text, spinner='dots', **kwargs):
    self.text = text
    self.spinner = spinner
    self.kwargs = kwargs

  def __call__(self, func):
    @wraps(func)
    def wrapped(*args, **kwargs):
      halo = Halo(text=self.text.format(*args, **kwargs), spinner=self.spinner)
      halo.start()
      func(*args, **kwargs)
      halo.succeed()
    return wrapped


@HaloExtend(text='Loading {task}', spinner='line')
def run_task(task):
  sleep(3)

tasks = ['breakfest', 'launch', 'dinner']

for task in tasks:
  run_task(task=task)
@liudonghua123
Copy link
Author

liudonghua123 commented Mar 24, 2021

I tried to refactor the above code using with/__enter__/__exit__ form, however I failed because the execution flow is __call__ (only once) -> __enter__ -> wrapped -> __exit__. And in the __enter__ I couldn't got args/kwargs, so the text could not substitute.

some helpful links:
https://www.geeksforgeeks.org/with-statement-in-python/
https://www.geeksforgeeks.org/python-functools-wraps-function/

LowLevelLover added a commit to LowLevelLover/halo that referenced this issue May 9, 2021
fix issue manrajgrover#157 -+- change decorator implementation -+- add an example of new decorator approach -+- it needs to write new tests but example work well
LowLevelLover added a commit to LowLevelLover/halo that referenced this issue May 9, 2021
@LowLevelLover LowLevelLover mentioned this issue May 9, 2021
3 tasks
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

Successfully merging a pull request may close this issue.

1 participant