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

Bunch of small tidy-ups for python 3 and pep8 standards #1482

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion .meta/mkcompletion.py
Expand Up @@ -34,7 +34,7 @@ def doc2opt(doc, user_input=True):
options_input &= options
options_input -= {"--log"} # manually dealt with
src_dir = path.abspath(path.dirname(__file__))
completion = u"""\
completion = """\
#!/usr/bin/env bash
_tqdm(){{
local cur prv
Expand Down
2 changes: 1 addition & 1 deletion examples/7zx.py
Expand Up @@ -59,7 +59,7 @@ def main():
for s in range(2): # size|compressed totals
totals_s = sum(map(int, (inf[s] for inf in finfo[:-1])))
if totals_s != totals[s]:
log.warn("%s: individual total %d != 7z total %d",
log.warning("%s: individual total %d != 7z total %d",
fn, totals_s, totals[s])
fcomp = {n: int(c if args.compressed else u) for (u, c, n) in finfo[:-1]}
# log.debug(fcomp)
Expand Down
2 changes: 1 addition & 1 deletion tests/tests_contrib_logging.py
@@ -1,5 +1,5 @@
# pylint: disable=missing-module-docstring, missing-class-docstring
# pylint: disable=missing-function-docstring, no-self-use
# pylint: disable=missing-function-docstring
import logging
import logging.handlers
import sys
Expand Down
2 changes: 1 addition & 1 deletion tests/tests_itertools.py
Expand Up @@ -8,7 +8,7 @@
from .tests_tqdm import StringIO, closing


class NoLenIter(object):
class NoLenIter():
def __init__(self, iterable):
self._it = iterable

Expand Down
6 changes: 3 additions & 3 deletions tests/tests_perf.py
Expand Up @@ -97,9 +97,9 @@ def format_interval(t):
mins, s = divmod(int(t), 60)
h, m = divmod(mins, 60)
if h:
return '{0:d}:{1:02d}:{2:02d}'.format(h, m, s)
return f'{h:d}:{m:02d}:{s:02d}'
else:
return '{0:02d}:{1:02d}'.format(m, s)
return f'{m:02d}:{s:02d}'

def update_and_print(i=1):
n[0] += i
Expand All @@ -112,7 +112,7 @@ def update_and_print(i=1):
spent = last_t[0] - start_t[0]
spent_fmt = format_interval(spent)
rate = n[0] / spent if spent > 0 else 0
rate_fmt = "%.2fs/it" % (1.0 / rate) if 0.0 < rate < 1.0 else "%.2fit/s" % rate
rate_fmt = f"{1.0 / rate:.2f}s/it" if 0.0 < rate < 1.0 else f"{rate:.2f}it/s"

frac = n[0] / total
percentage = int(frac * 100)
Expand Down
4 changes: 2 additions & 2 deletions tests/tests_synchronisation.py
Expand Up @@ -7,7 +7,7 @@
from .tests_tqdm import StringIO, closing, importorskip, patch_lock, skip


class Time(object):
class Time():
"""Fake time class class providing an offset"""
offset = 0

Expand Down Expand Up @@ -78,7 +78,7 @@ def cpu_timify(t, timer=Time):
return timer


class FakeTqdm(object):
class FakeTqdm():
_instances = set()
get_lock = tqdm.get_lock

Expand Down
42 changes: 21 additions & 21 deletions tests/tests_tqdm.py
Expand Up @@ -47,7 +47,7 @@ def closing(arg):
CTRLCHR = [r'\r', r'\n', r'\x1b\[A'] # Need to escape [ for regex
# Regular expressions compilation
RE_rate = re.compile(r'[^\d](\d[.\d]+)it/s')
RE_ctrlchr = re.compile("(%s)" % '|'.join(CTRLCHR)) # Match control chars
RE_ctrlchr = re.compile(f"({'|'.join(CTRLCHR)})") # Match control chars
RE_ctrlchr_excl = re.compile('|'.join(CTRLCHR)) # Match and exclude ctrl chars
RE_pos = re.compile(r'([\r\n]+((pos\d+) bar:\s+\d+%|\s{3,6})?[^\r\n]*)')

Expand Down Expand Up @@ -80,7 +80,7 @@ def pos_line_diff(res_list, expected_list, raise_nonempty=True):
return res


class DiscreteTimer(object):
class DiscreteTimer():
"""Virtual discrete time manager, to precisely control time for tests"""
def __init__(self):
self.t = 0.0
Expand All @@ -107,7 +107,7 @@ def cpu_timify(t, timer=None):
class UnicodeIO(IOBase):
"""Unicode version of StringIO"""
def __init__(self, *args, **kwargs):
super(UnicodeIO, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.encoding = 'U8' # io.StringIO supports unicode, but no encoding
self.text = ''
self.cursor = 0
Expand Down Expand Up @@ -315,11 +315,11 @@ def test_si_format():

def test_bar_formatspec():
"""Test Bar.__format__ spec"""
assert "{0:5a}".format(Bar(0.3)) == "#5 "
assert "{0:2}".format(Bar(0.5, charset=" .oO0")) == "0 "
assert "{0:2a}".format(Bar(0.5, charset=" .oO0")) == "# "
assert "{0:-6a}".format(Bar(0.5, 10)) == '## '
assert "{0:2b}".format(Bar(0.5, 10)) == ' '
assert f"{Bar(0.3):5a}" == "#5 "
assert f"{Bar(0.5, charset=' .oO0'):2}" == "0 "
assert f"{Bar(0.5, charset=' .oO0'):2a}" == "# "
assert f"{Bar(0.5, 10):-6a}" == '## '
assert f"{Bar(0.5, 10):2b}" == ' '


def test_all_defaults():
Expand All @@ -340,7 +340,7 @@ def test_all_defaults():
class WriteTypeChecker(BytesIO):
"""File-like to assert the expected type is written"""
def __init__(self, expected_type):
super(WriteTypeChecker, self).__init__()
super().__init__()
self.expected_type = expected_type

def write(self, s):
Expand All @@ -363,7 +363,7 @@ def test_native_string_io_for_default_file():

def test_unicode_string_io_for_specified_file():
"""Unicode strings written to specified files"""
for _ in tqdm(range(3), file=WriteTypeChecker(expected_type=type(u''))):
for _ in tqdm(range(3), file=WriteTypeChecker(expected_type=type(''))):
pass


Expand All @@ -376,7 +376,7 @@ def test_write_bytes():
# unspecified file (and unicode)
stderr = sys.stderr
try:
sys.stderr = WriteTypeChecker(expected_type=type(u''))
sys.stderr = WriteTypeChecker(expected_type=type(''))
for _ in tqdm(range(3), write_bytes=False):
pass
finally:
Expand Down Expand Up @@ -867,9 +867,9 @@ def test_ascii():
for _ in range(3):
t.update()
res = our_file.getvalue().strip("\r").split("\r")
assert u"7%|\u258b" in res[1]
assert u"13%|\u2588\u258e" in res[2]
assert u"20%|\u2588\u2588" in res[3]
assert "7%|\u258b" in res[1]
assert "13%|\u2588\u258e" in res[2]
assert "20%|\u2588\u2588" in res[3]

# Test custom bar
for bars in [" .oO0", " #"]:
Expand Down Expand Up @@ -1093,7 +1093,7 @@ class TqdmExtraFormat(tqdm):
"""Provides a `total_time` format parameter"""
@property
def format_dict(self):
d = super(TqdmExtraFormat, self).format_dict
d = super().format_dict
total_time = d["elapsed"] * (d["total"] or 0) / max(d["n"], 1)
d.update(total_time=self.format_interval(total_time) + " in total")
return d
Expand All @@ -1113,7 +1113,7 @@ def test_eta(capsys):
bar_format='{l_bar}{eta:%Y-%m-%d}'):
pass
_, err = capsys.readouterr()
assert "\r100%|{eta:%Y-%m-%d}\n".format(eta=dt.now()) in err
assert f"\r100%|{dt.now():%Y-%m-%d}\n" in err


def test_unpause():
Expand Down Expand Up @@ -1321,7 +1321,7 @@ def test_set_description():
# unicode
with closing(StringIO()) as our_file:
with tqdm(total=10, file=our_file) as t:
t.set_description(u"\xe1\xe9\xed\xf3\xfa")
t.set_description("\xe1\xe9\xed\xf3\xfa")


def test_deprecated_gui():
Expand Down Expand Up @@ -1444,8 +1444,8 @@ def test_refresh():
t2.close()

# Check that refreshing indeed forced the display to use realtime state
assert before == [u'pos0 bar: 0%|', u'pos1 bar: 0%|']
assert after == [u'pos0 bar: 10%|', u'pos1 bar: 10%|']
assert before == ['pos0 bar: 0%|', 'pos1 bar: 0%|']
assert after == ['pos0 bar: 10%|', 'pos1 bar: 10%|']


def test_disabled_repr(capsys):
Expand Down Expand Up @@ -1824,14 +1824,14 @@ def test_wrapattr():
res = writer.getvalue()
assert data == res
res = our_file.getvalue()
assert '%.1fB [' % len(data) in res
assert f'{len(data):.1f}B [' in res

with closing(StringIO()) as our_file:
with closing(StringIO()) as writer:
with tqdm.wrapattr(writer, "write", file=our_file, bytes=False) as wrap:
wrap.write(data)
res = our_file.getvalue()
assert '%dit [' % len(data) in res
assert f'{len(data)}it [' in res


def test_float_progress():
Expand Down
2 changes: 1 addition & 1 deletion tqdm/asyncio.py
Expand Up @@ -21,7 +21,7 @@ class tqdm_asyncio(std_tqdm):
Asynchronous-friendly version of tqdm.
"""
def __init__(self, iterable=None, *args, **kwargs):
super(tqdm_asyncio, self).__init__(iterable, *args, **kwargs)
super().__init__(iterable, *args, **kwargs)
self.iterable_awaitable = False
if iterable is not None:
if hasattr(iterable, "__anext__"):
Expand Down
4 changes: 2 additions & 2 deletions tqdm/cli.py
Expand Up @@ -235,7 +235,7 @@ def main(fp=sys.stderr, argv=None):
manpath = tqdm_args.pop('manpath', None)
comppath = tqdm_args.pop('comppath', None)
if tqdm_args.pop('null', False):
class stdout(object):
class stdout():
@staticmethod
def write(_):
pass
Expand Down Expand Up @@ -265,7 +265,7 @@ def cp(name, dst):
stdout_write = stdout.write
fp_write = getattr(fp, 'buffer', fp).write

class stdout(object): # pylint: disable=function-redefined
class stdout(): # pylint: disable=function-redefined
@staticmethod
def write(x):
with tqdm.external_write_mode(file=fp):
Expand Down
2 changes: 1 addition & 1 deletion tqdm/contrib/__init__.py
Expand Up @@ -17,7 +17,7 @@ class DummyTqdmFile(ObjectWrapper):
"""Dummy file-like that will write to tqdm"""

def __init__(self, wrapped):
super(DummyTqdmFile, self).__init__(wrapped)
super().__init__(wrapped)
self._buf = []

def write(self, x, nolock=False):
Expand Down
8 changes: 4 additions & 4 deletions tqdm/contrib/discord.py
Expand Up @@ -27,7 +27,7 @@ class DiscordIO(MonoWorker):
"""Non-blocking file-like IO using a Discord Bot."""
def __init__(self, token, channel_id):
"""Creates a new message in the given `channel_id`."""
super(DiscordIO, self).__init__()
super().__init__()
config = ClientConfig()
config.token = token
client = Client(config)
Expand Down Expand Up @@ -91,10 +91,10 @@ def __init__(self, *args, **kwargs):
kwargs.pop('token', getenv("TQDM_DISCORD_TOKEN")),
kwargs.pop('channel_id', getenv("TQDM_DISCORD_CHANNEL_ID")))
kwargs['mininterval'] = max(1.5, kwargs.get('mininterval', 1.5))
super(tqdm_discord, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)

def display(self, **kwargs):
super(tqdm_discord, self).display(**kwargs)
super().display(**kwargs)
fmt = self.format_dict
if fmt.get('bar_format', None):
fmt['bar_format'] = fmt['bar_format'].replace(
Expand All @@ -104,7 +104,7 @@ def display(self, **kwargs):
self.dio.write(self.format_meter(**fmt))

def clear(self, *args, **kwargs):
super(tqdm_discord, self).clear(*args, **kwargs)
super().clear(*args, **kwargs)
if not self.disable:
self.dio.write("")

Expand Down
2 changes: 1 addition & 1 deletion tqdm/contrib/logging.py
Expand Up @@ -18,7 +18,7 @@ def __init__(
self,
tqdm_class=std_tqdm # type: Type[std_tqdm]
):
super(_TqdmLoggingHandler, self).__init__()
super().__init__()
self.tqdm_class = tqdm_class

def emit(self, record):
Expand Down
8 changes: 4 additions & 4 deletions tqdm/contrib/slack.py
Expand Up @@ -27,7 +27,7 @@ class SlackIO(MonoWorker):
"""Non-blocking file-like IO using a Slack app."""
def __init__(self, token, channel):
"""Creates a new message in the given `channel`."""
super(SlackIO, self).__init__()
super().__init__()
self.client = WebClient(token=token)
self.text = self.__class__.__name__
try:
Expand Down Expand Up @@ -88,10 +88,10 @@ def __init__(self, *args, **kwargs):
kwargs.pop('token', getenv("TQDM_SLACK_TOKEN")),
kwargs.pop('channel', getenv("TQDM_SLACK_CHANNEL")))
kwargs['mininterval'] = max(1.5, kwargs.get('mininterval', 1.5))
super(tqdm_slack, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)

def display(self, **kwargs):
super(tqdm_slack, self).display(**kwargs)
super().display(**kwargs)
fmt = self.format_dict
if fmt.get('bar_format', None):
fmt['bar_format'] = fmt['bar_format'].replace(
Expand All @@ -105,7 +105,7 @@ def display(self, **kwargs):
self.sio.write(self.format_meter(**fmt))

def clear(self, *args, **kwargs):
super(tqdm_slack, self).clear(*args, **kwargs)
super().clear(*args, **kwargs)
if not self.disable:
self.sio.write("")

Expand Down
16 changes: 8 additions & 8 deletions tqdm/contrib/telegram.py
Expand Up @@ -27,7 +27,7 @@ class TelegramIO(MonoWorker):

def __init__(self, token, chat_id):
"""Creates a new message in the given `chat_id`."""
super(TelegramIO, self).__init__()
super().__init__()
self.token = token
self.chat_id = chat_id
self.session = Session()
Expand All @@ -40,7 +40,7 @@ def message_id(self):
return self._message_id
try:
res = self.session.post(
self.API + '%s/sendMessage' % self.token,
self.API + f'{self.token}/sendMessage',
data={'text': '`' + self.text + '`', 'chat_id': self.chat_id,
'parse_mode': 'MarkdownV2'}).json()
except Exception as e:
Expand All @@ -66,7 +66,7 @@ def write(self, s):
self.text = s
try:
future = self.submit(
self.session.post, self.API + '%s/editMessageText' % self.token,
self.session.post, self.API + f'{self.token}/editMessageText',
data={'text': '`' + s + '`', 'chat_id': self.chat_id,
'message_id': message_id, 'parse_mode': 'MarkdownV2'})
except Exception as e:
Expand All @@ -78,7 +78,7 @@ def delete(self):
"""Deletes internal `message_id`."""
try:
future = self.submit(
self.session.post, self.API + '%s/deleteMessage' % self.token,
self.session.post, self.API + f'{self.token}/deleteMessage',
data={'chat_id': self.chat_id, 'message_id': self.message_id})
except Exception as e:
tqdm_auto.write(str(e))
Expand Down Expand Up @@ -118,10 +118,10 @@ def __init__(self, *args, **kwargs):
self.tgio = TelegramIO(
kwargs.pop('token', getenv('TQDM_TELEGRAM_TOKEN')),
kwargs.pop('chat_id', getenv('TQDM_TELEGRAM_CHAT_ID')))
super(tqdm_telegram, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)

def display(self, **kwargs):
super(tqdm_telegram, self).display(**kwargs)
super().display(**kwargs)
fmt = self.format_dict
if fmt.get('bar_format', None):
fmt['bar_format'] = fmt['bar_format'].replace(
Expand All @@ -131,14 +131,14 @@ def display(self, **kwargs):
self.tgio.write(self.format_meter(**fmt))

def clear(self, *args, **kwargs):
super(tqdm_telegram, self).clear(*args, **kwargs)
super().clear(*args, **kwargs)
if not self.disable:
self.tgio.write("")

def close(self):
if self.disable:
return
super(tqdm_telegram, self).close()
super().close()
if not (self.leave or (self.leave is None and self.pos == 0)):
self.tgio.delete()

Expand Down
2 changes: 1 addition & 1 deletion tqdm/contrib/utils_worker.py
Expand Up @@ -10,7 +10,7 @@
__all__ = ['MonoWorker']


class MonoWorker(object):
class MonoWorker():
"""
Supports one running task and one waiting task.
The waiting task is the most recent submitted (others are discarded).
Expand Down