Using possibly undefined loop variable 'df_g'
42
43 def means_by_parts(df, cols_in, cols_out):
44 df = df.ix[:, cols_in]
45 data = df.groupby(pd.cut(df_g.index, bins=parts)).mean() 46 data.index = part_names[: len(data.index)]
47 data.columns = cols_out
48
Using possibly undefined loop variable 'row'
74 first_line = False
75
76 if endfilefunc is not None:
77 endfilefunc(row) 78
79 if wltc_class not in wltc_data_files:
80 raise ValueError(
Using possibly undefined loop variable 'val'
253
254 if isinstance(val, pd.DataFrame):
255 val = [panda2col(col_tuple[1]) for col_tuple in val.iteritems()]
256 elif isinstance(val, pd.Series):257 val = val.to_numpy().reshape(-1, 1)
258 return val
259
Description
Using a loop variable (i.e. defined by a for loop or a list comprehension or a generator expression) outside the loop can create subtle bugs, like the variable not being defined if the list was empty. Generally, you should avoid using loop variables outside the loop, or define them early.
Bad practice
for i in items:
if item_name(i) == "coffee":
price = calculate_cost(i)
print(price) # raises `NameError` if `items` is empty
Preferred:
price = None # Define variable outside loop
for i in items:
if item_name(i) == "coffee":
price = calculate_cost(i)
print(price)