Skip to content

Commit

Permalink
get rid of get_new
Browse files Browse the repository at this point in the history
- fixes #1084
- fixes #509
  • Loading branch information
casperdcl committed Nov 27, 2020
1 parent bded8fa commit 9224b7b
Show file tree
Hide file tree
Showing 6 changed files with 5 additions and 79 deletions.
21 changes: 1 addition & 20 deletions .meta/.readme.rst
Expand Up @@ -919,9 +919,7 @@ For further customisation,
(e.g. GUIs such as notebook or plotting packages). In the latter case:

1. ``def __init__()`` to call ``super().__init__(..., gui=True)`` to disable
terminal ``status_printer`` creation. Otherwise (if terminal is required),
``def __new__()`` to call ``cls.get_new()`` (see below) to ensure correct
nested positioning.
terminal ``status_printer`` creation.
2. Redefine: ``close()``, ``clear()``, ``display()``.

Consider overloading ``display()`` to use e.g.
Expand All @@ -935,23 +933,6 @@ above recommendation:
- `tqdm/contrib/telegram.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/telegram.py>`__
- `tqdm/contrib/discord.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/discord.py>`__

Note that multiple different ``tqdm`` subclasses which all write to the terminal
(``gui=False``) can cause positioning issues when used simultaneously (in nested
mode). To fix this, custom subclasses which expect to write to the terminal
should define a ``__new__()`` method as follows:

.. code:: python
from tqdm import tqdm as std_tqdm
class TqdmExt(std_tqdm):
def __new__(cls, *args, **kwargs):
return cls.get_new(super(TqdmExt, cls), std_tqdm, *args, **kwargs)
This approach is used ``tqdm.asyncio`` and ``tqdm.contrib.telegram/discord``.
However it is not necessary for ``tqdm.notebook/gui`` since they don't use the
terminal.

Dynamic Monitor/Meter
~~~~~~~~~~~~~~~~~~~~~

Expand Down
21 changes: 1 addition & 20 deletions README.rst
Expand Up @@ -1136,9 +1136,7 @@ For further customisation,
(e.g. GUIs such as notebook or plotting packages). In the latter case:

1. ``def __init__()`` to call ``super().__init__(..., gui=True)`` to disable
terminal ``status_printer`` creation. Otherwise (if terminal is required),
``def __new__()`` to call ``cls.get_new()`` (see below) to ensure correct
nested positioning.
terminal ``status_printer`` creation.
2. Redefine: ``close()``, ``clear()``, ``display()``.

Consider overloading ``display()`` to use e.g.
Expand All @@ -1152,23 +1150,6 @@ above recommendation:
- `tqdm/contrib/telegram.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/telegram.py>`__
- `tqdm/contrib/discord.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/discord.py>`__

Note that multiple different ``tqdm`` subclasses which all write to the terminal
(``gui=False``) can cause positioning issues when used simultaneously (in nested
mode). To fix this, custom subclasses which expect to write to the terminal
should define a ``__new__()`` method as follows:

.. code:: python
from tqdm import tqdm as std_tqdm
class TqdmExt(std_tqdm):
def __new__(cls, *args, **kwargs):
return cls.get_new(super(TqdmExt, cls), std_tqdm, *args, **kwargs)
This approach is used ``tqdm.asyncio`` and ``tqdm.contrib.telegram/discord``.
However it is not necessary for ``tqdm.notebook/gui`` since they don't use the
terminal.

Dynamic Monitor/Meter
~~~~~~~~~~~~~~~~~~~~~

Expand Down
3 changes: 0 additions & 3 deletions tqdm/asyncio.py
Expand Up @@ -62,9 +62,6 @@ def as_completed(cls, fs, *, loop=None, timeout=None, total=None,
yield from cls(asyncio.as_completed(fs, loop=loop, timeout=timeout),
total=total, **tqdm_kwargs)

def __new__(cls, *args, **kwargs):
return cls.get_new(super(tqdm_asyncio, cls), std_tqdm, *args, **kwargs)


def tarange(*args, **kwargs):
"""
Expand Down
3 changes: 0 additions & 3 deletions tqdm/contrib/discord.py
Expand Up @@ -102,9 +102,6 @@ def display(self, **kwargs):
fmt['bar_format'] = '{l_bar}{bar:10u}{r_bar}'
self.dio.write(self.format_meter(**fmt))

def __new__(cls, *args, **kwargs):
return cls.get_new(super(tqdm_discord, cls), tqdm_auto, *args, **kwargs)


def tdrange(*args, **kwargs):
"""
Expand Down
4 changes: 0 additions & 4 deletions tqdm/contrib/telegram.py
Expand Up @@ -106,10 +106,6 @@ def display(self, **kwargs):
fmt['bar_format'] = '{l_bar}{bar:10u}{r_bar}'
self.tgio.write(self.format_meter(**fmt))

def __new__(cls, *args, **kwargs):
return cls.get_new(
super(tqdm_telegram, cls), tqdm_auto, *args, **kwargs)


def ttgrange(*args, **kwargs):
"""
Expand Down
32 changes: 3 additions & 29 deletions tqdm/std.py
Expand Up @@ -225,6 +225,7 @@ class tqdm(Comparable):

monitor_interval = 10 # set to 0 to disable the thread
monitor = None
_instances = WeakSet()

@staticmethod
def format_sizeof(num, suffix='', divisor=1000):
Expand Down Expand Up @@ -554,15 +555,10 @@ def format_meter(n, total, elapsed, ncols=None, prefix='', ascii=False,
n_fmt, unit, elapsed_str, rate_fmt, postfix)

def __new__(cls, *_, **__):
# Create a new instance
instance = object.__new__(cls)
# Construct the lock if it does not exist
with cls.get_lock():
# Add to the list of instances
if not hasattr(cls, '_instances'):
cls._instances = WeakSet()
with cls.get_lock(): # also constructs lock if non-existent
cls._instances.add(instance)
# Create the monitoring thread
# create monitoring thread
if cls.monitor_interval and (cls.monitor is None or not
cls.monitor.report()):
try:
Expand All @@ -572,28 +568,6 @@ def __new__(cls, *_, **__):
" (monitor_interval = 0) due to:\n" + str(e),
TqdmMonitorWarning, stacklevel=2)
cls.monitor_interval = 0
# Return the instance
return instance

@classmethod
def get_new(cls, super_cls, base_cls, *args, **kwargs):
"""
Workaround for mixed-class same-stream nested progressbars.
See [#509](https://github.com/tqdm/tqdm/issues/509)
"""
with cls.get_lock():
try:
cls._instances = base_cls._instances
except AttributeError:
pass
instance = super_cls.__new__(cls, *args, **kwargs)
with cls.get_lock():
try:
# `base_cls` may have been changed so update
cls._instances.update(base_cls._instances)
except AttributeError:
pass
base_cls._instances = cls._instances
return instance

@classmethod
Expand Down

0 comments on commit 9224b7b

Please sign in to comment.