Skip to content

Commit 1a61e26

Browse files
JustinZhengBCdatapythonista
authored andcommitted
CLN: Replace bare excepts by explicit excepts in pandas/io/ (#23004)
1 parent f6da1f1 commit 1a61e26

File tree

10 files changed

+30
-28
lines changed

10 files changed

+30
-28
lines changed

pandas/io/clipboards.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def read_clipboard(sep=r'\s+', **kwargs): # pragma: no cover
4242
text, encoding=(kwargs.get('encoding') or
4343
get_option('display.encoding'))
4444
)
45-
except:
45+
except AttributeError:
4646
pass
4747

4848
# Excel copies into clipboard with \t separation

pandas/io/formats/console.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ def check_main():
100100

101101
try:
102102
return __IPYTHON__ or check_main() # noqa
103-
except:
103+
except NameError:
104104
return check_main()
105105

106106

@@ -118,7 +118,7 @@ def in_qtconsole():
118118
ip.config.get('IPKernelApp', {}).get('parent_appname', ""))
119119
if 'qtconsole' in front_end.lower():
120120
return True
121-
except:
121+
except NameError:
122122
return False
123123
return False
124124

@@ -137,7 +137,7 @@ def in_ipnb():
137137
ip.config.get('IPKernelApp', {}).get('parent_appname', ""))
138138
if 'notebook' in front_end.lower():
139139
return True
140-
except:
140+
except NameError:
141141
return False
142142
return False
143143

@@ -149,7 +149,7 @@ def in_ipython_frontend():
149149
try:
150150
ip = get_ipython() # noqa
151151
return 'zmq' in str(type(ip)).lower()
152-
except:
152+
except NameError:
153153
pass
154154

155155
return False

pandas/io/formats/terminal.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def _get_terminal_size_windows():
7878
h = windll.kernel32.GetStdHandle(-12)
7979
csbi = create_string_buffer(22)
8080
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
81-
except:
81+
except (AttributeError, ValueError):
8282
return None
8383
if res:
8484
import struct
@@ -108,7 +108,7 @@ def _get_terminal_size_tput():
108108
output = proc.communicate(input=None)
109109
rows = int(output[0])
110110
return (cols, rows)
111-
except:
111+
except OSError:
112112
return None
113113

114114

@@ -120,7 +120,7 @@ def ioctl_GWINSZ(fd):
120120
import struct
121121
cr = struct.unpack(
122122
'hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
123-
except:
123+
except (struct.error, IOError):
124124
return None
125125
return cr
126126
cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
@@ -129,13 +129,13 @@ def ioctl_GWINSZ(fd):
129129
fd = os.open(os.ctermid(), os.O_RDONLY)
130130
cr = ioctl_GWINSZ(fd)
131131
os.close(fd)
132-
except:
132+
except OSError:
133133
pass
134134
if not cr or cr == (0, 0):
135135
try:
136136
from os import environ as env
137137
cr = (env['LINES'], env['COLUMNS'])
138-
except:
138+
except (ValueError, KeyError):
139139
return None
140140
return int(cr[1]), int(cr[0])
141141

pandas/io/packers.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,7 @@ def read(fh):
196196
if should_close:
197197
try:
198198
path_or_buf.close()
199-
except: # noqa: flake8
199+
except IOError:
200200
pass
201201
return unpacked_obj
202202

@@ -705,7 +705,7 @@ def create_block(b):
705705
dtype = dtype_for(obj[u'dtype'])
706706
try:
707707
return dtype(obj[u'data'])
708-
except:
708+
except (ValueError, TypeError):
709709
return dtype.type(obj[u'data'])
710710
elif typ == u'np_complex':
711711
return complex(obj[u'real'] + u'+' + obj[u'imag'] + u'j')

pandas/io/parsers.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -459,7 +459,7 @@ def _read(filepath_or_buffer, kwds):
459459
if should_close:
460460
try:
461461
filepath_or_buffer.close()
462-
except: # noqa: flake8
462+
except ValueError:
463463
pass
464464

465465
return data
@@ -1808,7 +1808,7 @@ def close(self):
18081808
# close additional handles opened by C parser (for compression)
18091809
try:
18101810
self._reader.close()
1811-
except:
1811+
except ValueError:
18121812
pass
18131813

18141814
def _set_noconvert_columns(self):
@@ -3034,7 +3034,7 @@ def converter(*date_cols):
30343034
errors='ignore',
30353035
infer_datetime_format=infer_datetime_format
30363036
)
3037-
except:
3037+
except ValueError:
30383038
return tools.to_datetime(
30393039
parsing.try_parse_dates(strs, dayfirst=dayfirst))
30403040
else:
@@ -3263,7 +3263,7 @@ def _floatify_na_values(na_values):
32633263
v = float(v)
32643264
if not np.isnan(v):
32653265
result.add(v)
3266-
except:
3266+
except (TypeError, ValueError, OverflowError):
32673267
pass
32683268
return result
32693269

@@ -3284,11 +3284,11 @@ def _stringify_na_values(na_values):
32843284
result.append(str(v))
32853285

32863286
result.append(v)
3287-
except:
3287+
except (TypeError, ValueError, OverflowError):
32883288
pass
32893289
try:
32903290
result.append(int(x))
3291-
except:
3291+
except (TypeError, ValueError, OverflowError):
32923292
pass
32933293
return set(result)
32943294

pandas/io/pickle.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -163,18 +163,20 @@ def try_read(path, encoding=None):
163163
# We want to silence any warnings about, e.g. moved modules.
164164
warnings.simplefilter("ignore", Warning)
165165
return read_wrapper(lambda f: pkl.load(f))
166-
except Exception:
166+
except Exception: # noqa: E722
167167
# reg/patched pickle
168+
# compat not used in pandas/compat/pickle_compat.py::load
169+
# TODO: remove except block OR modify pc.load to use compat
168170
try:
169171
return read_wrapper(
170172
lambda f: pc.load(f, encoding=encoding, compat=False))
171173
# compat pickle
172-
except:
174+
except Exception: # noqa: E722
173175
return read_wrapper(
174176
lambda f: pc.load(f, encoding=encoding, compat=True))
175177
try:
176178
return try_read(path)
177-
except:
179+
except Exception: # noqa: E722
178180
if PY3:
179181
return try_read(path, encoding='latin1')
180182
raise

pandas/io/sas/sas_xport.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,7 @@ def __init__(self, filepath_or_buffer, index=None, encoding='ISO-8859-1',
246246
contents = filepath_or_buffer.read()
247247
try:
248248
contents = contents.encode(self._encoding)
249-
except:
249+
except UnicodeEncodeError:
250250
pass
251251
self.filepath_or_buffer = compat.BytesIO(contents)
252252

pandas/io/sas/sasreader.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def read_sas(filepath_or_buffer, format=None, index=None, encoding=None,
4646
format = "sas7bdat"
4747
else:
4848
raise ValueError("unable to infer format of SAS file")
49-
except:
49+
except ValueError:
5050
pass
5151

5252
if format.lower() == 'xport':

pandas/io/sql.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -382,7 +382,7 @@ def read_sql(sql, con, index_col=None, coerce_float=True, params=None,
382382

383383
try:
384384
_is_table_name = pandas_sql.has_table(sql)
385-
except:
385+
except (ImportError, AttributeError):
386386
_is_table_name = False
387387

388388
if _is_table_name:
@@ -847,7 +847,7 @@ def _sqlalchemy_type(self, col):
847847
try:
848848
tz = col.tzinfo # noqa
849849
return DateTime(timezone=True)
850-
except:
850+
except AttributeError:
851851
return DateTime
852852
if col_type == 'timedelta64':
853853
warnings.warn("the 'timedelta' type is not supported, and will be "
@@ -1360,7 +1360,7 @@ def run_transaction(self):
13601360
try:
13611361
yield cur
13621362
self.con.commit()
1363-
except:
1363+
except Exception:
13641364
self.con.rollback()
13651365
raise
13661366
finally:

pandas/io/stata.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1252,12 +1252,12 @@ def _read_old_header(self, first_char):
12521252

12531253
try:
12541254
self.typlist = [self.TYPE_MAP[typ] for typ in typlist]
1255-
except:
1255+
except ValueError:
12561256
raise ValueError("cannot convert stata types [{0}]"
12571257
.format(','.join(str(x) for x in typlist)))
12581258
try:
12591259
self.dtyplist = [self.DTYPE_MAP[typ] for typ in typlist]
1260-
except:
1260+
except ValueError:
12611261
raise ValueError("cannot convert stata dtypes [{0}]"
12621262
.format(','.join(str(x) for x in typlist)))
12631263

0 commit comments

Comments
 (0)