Skip to content

fix: make utils.tqdm thread-safe #3286

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 17 additions & 11 deletions src/huggingface_hub/utils/tqdm.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,27 +211,33 @@ def is_tqdm_disabled(log_level: int) -> Optional[bool]:
return None


class tqdm(old_tqdm):
class SafeDelLockMeta(type):
"""
Class for fixing `del tqdm_class._lock`: https://github.com/huggingface/datasets/issues/7660
"""

def __delattr__(cls, name):
if name == "_lock":
try:
super().__delattr__(name)
except AttributeError:
pass
else:
super().__delattr__(name)


class tqdm(old_tqdm, metaclass=SafeDelLockMeta):
"""
Class to override `disable` argument in case progress bars are globally disabled.

Taken from https://github.com/tqdm/tqdm/issues/619#issuecomment-619639324.
"""

def __init__(self, *args, **kwargs):
name = kwargs.pop("name", None) # do not pass `name` to `tqdm`
if are_progress_bars_disabled(name):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there a reason why dropping the original __init__ and __delattr__?
even when keeping the original __delattr__, del tqdm._lock will call SafeDelLockMeta.__delattr__ (which safeguards the class level race only).

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you are definitely correct, thanks for the suggestions. now the PR is updated.

if are_progress_bars_disabled():
kwargs["disable"] = True
super().__init__(*args, **kwargs)

def __delattr__(self, attr: str) -> None:
"""Fix for https://github.com/huggingface/huggingface_hub/issues/1603"""
try:
super().__delattr__(attr)
except AttributeError:
if attr != "_lock":
raise


@contextmanager
def tqdm_stream_file(path: Union[Path, str]) -> Iterator[io.BufferedReader]:
Expand Down
Loading