Skip to content

Commit c2941fb

Browse files
committed
spring clean (mostly pragma)
1 parent 0b19c2b commit c2941fb

8 files changed

Lines changed: 100 additions & 128 deletions

File tree

setup.py

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,23 +7,22 @@
77
except ImportError:
88
from distutils.core import setup
99
import sys
10-
import subprocess
10+
from subprocess import check_call
11+
from io import open
12+
1113
# For Makefile parsing
1214
import shlex
1315
try: # pragma: no cover
1416
import ConfigParser
1517
import StringIO
1618
except ImportError: # pragma: no cover
17-
# Python 3 compatibility
1819
import configparser as ConfigParser
1920
import io as StringIO
20-
import io
2121
import re
2222

2323

2424
""" Makefile auxiliary functions """
2525

26-
2726
RE_MAKE_CMD = re.compile('^\t(@\+?)(make)?', flags=re.M)
2827

2928

@@ -38,7 +37,7 @@ def parse_makefile_aliases(filepath):
3837
# -- Parsing the Makefile using ConfigParser
3938
# Adding a fake section to make the Makefile a valid Ini file
4039
ini_str = '[root]\n'
41-
with io.open(filepath, mode='r') as fd:
40+
with open(filepath, mode='r') as fd:
4241
ini_str = ini_str + RE_MAKE_CMD.sub('\t', fd.read())
4342
ini_fp = StringIO.StringIO(ini_str)
4443
# Parse using ConfigParser
@@ -114,16 +113,15 @@ def execute_makefile_commands(commands, alias, verbose=False):
114113
if verbose:
115114
print("Running command: " + cmd)
116115
# Launch the command and wait to finish (synchronized call)
117-
subprocess.check_call(parsed_cmd)
116+
check_call(parsed_cmd)
118117

119118

120119
""" Main setup.py config """
121120

122-
123121
# Get version from tqdm/_version.py
124122
__version__ = None
125123
version_file = os.path.join(os.path.dirname(__file__), 'tqdm', '_version.py')
126-
with io.open(version_file, mode='r') as fd:
124+
with open(version_file, mode='r') as fd:
127125
exec(fd.read())
128126

129127
# Executing makefile commands if specified
@@ -158,9 +156,8 @@ def execute_makefile_commands(commands, alias, verbose=False):
158156

159157
""" Python package config """
160158

161-
162159
README_rst = ''
163-
with io.open('README.rst', mode='r', encoding='utf-8') as fd:
160+
with open('README.rst', mode='r', encoding='utf-8') as fd:
164161
README_rst = fd.read()
165162

166163
setup(

tqdm/_main.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -31,17 +31,17 @@ def cast(val, typ):
3131
raise TqdmTypeError(val + ' : ' + typ)
3232

3333

34-
def posix_pipe(fin, fout, delim='\n', buf_size=256, callback=None):
34+
def posix_pipe(fin, fout, delim='\n', buf_size=256,
35+
callback=lambda int: None # pragma: no cover
36+
):
3537
"""
3638
Params
3739
------
3840
fin : file with `read(buf_size : int)` method
3941
fout : file with `write` (and optionally `flush`) methods.
4042
callback : function(int), e.g.: `tqdm.update`
4143
"""
42-
if callback is None: # pragma: no cover
43-
def callback(i):
44-
pass
44+
fp_write = fout.write
4545

4646
buf = ''
4747
tmp = ''
@@ -52,7 +52,7 @@ def callback(i):
5252
# flush at EOF
5353
if not tmp:
5454
if buf:
55-
fout.write(buf)
55+
fp_write(buf)
5656
callback(1 + buf.count(delim)) # n += 1 + buf.count(delim)
5757
getattr(fout, 'flush', lambda: None)() # pragma: no cover
5858
return # n
@@ -64,7 +64,7 @@ def callback(i):
6464
buf += tmp
6565
break
6666
else:
67-
fout.write(buf + tmp[:i + len(delim)])
67+
fp_write(buf + tmp[:i + len(delim)])
6868
callback(1) # n += 1
6969
buf = ''
7070
tmp = tmp[i + len(delim):]
@@ -133,7 +133,12 @@ def main():
133133
except KeyError as e:
134134
raise TqdmKeyError(str(e))
135135
# sys.stderr.write('\ndebug | args: ' + str(tqdm_args) + '\n')
136-
136+
except:
137+
sys.stderr.write('\nError:\nUsage:\n tqdm [--help | options]\n')
138+
for i in sys.stdin:
139+
sys.stdout.write(i)
140+
raise
141+
else:
137142
delim = tqdm_args.pop('delim', '\n')
138143
buf_size = tqdm_args.pop('buf_size', 256)
139144
if delim == '\n':
@@ -143,8 +148,3 @@ def main():
143148
with tqdm(**tqdm_args) as t:
144149
posix_pipe(sys.stdin, sys.stdout,
145150
delim, buf_size, t.update)
146-
except: # pragma: no cover
147-
sys.stderr.write('\nError:\nUsage:\n tqdm [--help | options]\n')
148-
for i in sys.stdin:
149-
sys.stdout.write(i)
150-
raise

tqdm/_tqdm.py

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -85,19 +85,17 @@ def status_printer(file):
8585
updating may not work (it will print a new line at each refresh).
8686
"""
8787
fp = file
88-
if not getattr(fp, 'flush', False): # pragma: no cover
89-
fp.flush = lambda: None
88+
fp_flush = getattr(fp, 'flush', lambda: None) # pragma: no cover
9089

9190
def fp_write(s):
9291
fp.write(_unicode(s))
92+
fp_flush()
9393

94-
last_printed_len = [0] # closure over mutable variable (fast)
95-
94+
last_len = [0]
9695
def print_status(s):
9796
len_s = len(s)
98-
fp_write('\r' + s + (' ' * max(last_printed_len[0] - len_s, 0)))
99-
fp.flush()
100-
last_printed_len[0] = len_s
97+
fp_write('\r' + s + (' ' * max(last_len[0] - len_s, 0)))
98+
last_len[0] = len_s
10199
return print_status
102100

103101
@staticmethod
@@ -305,20 +303,21 @@ def write(cls, s, file=sys.stdout, end="\n"):
305303
"""
306304
Print a message via tqdm (without overlap with bars)
307305
"""
306+
fp = file
307+
308308
# Clear all bars
309309
inst_cleared = []
310310
for inst in cls._instances:
311311
# Clear instance if in the target output file
312312
# or if write output + tqdm output are both either
313313
# sys.stdout or sys.stderr (because both are mixed in terminal)
314-
if inst.fp == file or \
315-
(file in [sys.stdout, sys.stderr] and
316-
inst.fp in [sys.stdout, sys.stderr]):
314+
if inst.fp == fp or all(f in (sys.stdout, sys.stderr)
315+
for f in (fp, inst.fp)):
317316
inst.clear()
318317
inst_cleared.append(inst)
319318
# Write the message
320-
file.write(s)
321-
file.write(end)
319+
fp.write(s)
320+
fp.write(end)
322321
# Force refresh display of bars we cleared
323322
for inst in inst_cleared:
324323
inst.refresh()
@@ -434,11 +433,11 @@ def __init__(self, iterable=None, desc=None, total=None, leave=True,
434433
total = None
435434

436435
if ((ncols is None) and (file in (sys.stderr, sys.stdout))) or \
437-
dynamic_ncols:
438-
if dynamic_ncols: # pragma: no cover
436+
dynamic_ncols: # pragma: no cover
437+
if dynamic_ncols:
439438
dynamic_ncols = _environ_cols_wrapper()
440439
ncols = dynamic_ncols(file)
441-
else: # pragma: no cover
440+
else:
442441
ncols = _environ_cols_wrapper()(file)
443442

444443
if miniters is None:

tqdm/_tqdm_gui.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ def __iter__(self):
148148
if delta_it >= miniters:
149149
cur_t = time()
150150
delta_t = cur_t - last_print_t
151-
if delta_t >= mininterval: # pragma: no cover
151+
if delta_t >= mininterval:
152152
elapsed = cur_t - start_t
153153
# EMA (not just overall average)
154154
if smoothing and delta_t:

tqdm/_tqdm_notebook.py

Lines changed: 36 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -17,71 +17,57 @@
1717
from ._tqdm import tqdm
1818

1919

20-
# import IPython/Jupyter base widget and display utilities
21-
try: # pragma: no cover
22-
# For IPython 4.x using ipywidgets
23-
import ipywidgets
24-
except ImportError: # pragma: no cover
25-
# For IPython 3.x / 2.x
26-
import warnings
27-
with warnings.catch_warnings():
28-
ipy_deprecation_msg = "The `IPython.html` package has been deprecated"
29-
warnings.filterwarnings('error',
30-
message=".*" + ipy_deprecation_msg + ".*")
31-
try:
32-
import IPython.html.widgets as ipywidgets
33-
except Warning as e:
34-
if ipy_deprecation_msg not in str(e):
35-
raise
36-
warnings.simplefilter('ignore')
20+
if True: # pragma: no cover
21+
# import IPython/Jupyter base widget and display utilities
22+
try: # IPython 4.x
23+
import ipywidgets
24+
except ImportError: # IPython 3.x / 2.x
25+
import warnings
26+
with warnings.catch_warnings():
27+
ipy_deprecation_msg = "The `IPython.html` package" \
28+
" has been deprecated"
29+
warnings.filterwarnings('error',
30+
message=".*" + ipy_deprecation_msg + ".*")
3731
try:
38-
import IPython.html.widgets as ipywidgets # NOQA
32+
import IPython.html.widgets as ipywidgets
33+
except Warning as e:
34+
if ipy_deprecation_msg not in str(e):
35+
raise
36+
warnings.simplefilter('ignore')
37+
try:
38+
import IPython.html.widgets as ipywidgets # NOQA
39+
except ImportError:
40+
pass
3941
except ImportError:
4042
pass
43+
44+
try: # IPython 4.x / 3.x
45+
from ipywidgets import IntProgress, HBox, HTML
46+
except ImportError:
47+
try: # IPython 2.x
48+
from ipywidgets import IntProgressWidget as IntProgress
49+
from ipywidgets import ContainerWidget as HBox
50+
from ipywidgets import HTML
4151
except ImportError:
4252
pass
4353

44-
try: # pragma: no cover
45-
# For IPython 4.x / 3.x
46-
from ipywidgets import IntProgress, HBox, HTML
47-
except ImportError: # pragma: no cover
4854
try:
49-
# For IPython 2.x
50-
from ipywidgets import IntProgressWidget as IntProgress
51-
from ipywidgets import ContainerWidget as HBox
52-
from ipywidgets import HTML
55+
from IPython.display import display # , clear_output
5356
except ImportError:
54-
# from ._tqdm import tqdm, trange
55-
# def warnWrap(fn, msg):
56-
# def inner(*args, **kwargs):
57-
# from sys import stderr
58-
# stderr.write(msg)
59-
# return fn(*args, **kwargs)
60-
# return inner
61-
# tqdm_notebook = warnWrap(tqdm, "Warning:\n\tNo ipywidgets."
62-
# "\ntFalling back to `tqdm`.\n")
63-
# tnrange = warnWrap(trange, "Warning:\n\tNo ipywidgets."
64-
# "\n\tFalling back to `trange`.\n")
65-
# exit
6657
pass
6758

68-
try: # pragma: no cover
69-
from IPython.display import display # , clear_output
70-
except ImportError: # pragma: no cover
71-
pass
72-
73-
# HTML encoding
74-
try: # pragma: no cover
75-
from html import escape # python 3.x
76-
except ImportError: # pragma: no cover
77-
from cgi import escape # python 2.x
59+
# HTML encoding
60+
try: # Py3
61+
from html import escape
62+
except ImportError: # Py2
63+
from cgi import escape
7864

7965

8066
__author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]}
8167
__all__ = ['tqdm_notebook', 'tnrange']
8268

8369

84-
class tqdm_notebook(tqdm): # pragma: no cover
70+
class tqdm_notebook(tqdm):
8571
"""
8672
Experimental IPython/Jupyter Notebook widget using tqdm!
8773
"""
@@ -97,8 +83,6 @@ def status_printer(file, total=None, desc=None):
9783
# return super(tqdm_notebook, tqdm_notebook).status_printer(file)
9884

9985
fp = file
100-
if not getattr(fp, 'flush', False): # pragma: no cover
101-
fp.flush = lambda: None
10286

10387
# Prepare IPython progress bar
10488
if total:
@@ -224,7 +208,7 @@ def moveto(*args, **kwargs):
224208
return
225209

226210

227-
def tnrange(*args, **kwargs): # pragma: no cover
211+
def tnrange(*args, **kwargs):
228212
"""
229213
A shortcut for tqdm_notebook(xrange(*args), **kwargs).
230214
On Python3+ range is used instead of xrange.

tqdm/_tqdm_pandas.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
__all__ = ['tqdm_pandas']
88

99

10-
def tqdm_pandas(t): # pragma: no cover
10+
def tqdm_pandas(t):
1111
"""
1212
Registers the given `tqdm` instance with
1313
`pandas.core.groupby.DataFrameGroupBy.progress_apply`.

0 commit comments

Comments
 (0)