A little background-- I have a Python program that makes plots from CSV files. I'm trying to make it more flexible by allowing a user to input between 1 and 3 files. I import the csv data into pandas data frames that are then used to generate a number of different plots.
I'm sure there's a better way to do what I'm doing, but I came across something strange (to me, at least) in my initial attempt to figure out if a user had input less than the maximum number of files.
Here is how I import the data:
# Imports the data. The first two rows must be skipped due to the file format
data1 = pd.read_csv(filename1, skiprows=1, header=True)
if filename2 != '':
data2 = pd.read_csv(filename2, skiprows=1, header=True)
if filename3 != '':
data3 = pd.read_csv(filename3, skiprows=1, header=True)
So data2
and data3
are only defined if a user has provided a file name from my GUI. Later, I just wanted to use the existence of data2
and data3
to determine whether or not to plot the 2nd and 3rd data sets, respectively:
try:
axarr[1, 0].psd(data1[Ynew], NFFT=n_samples, Fs=fs, noverlap=n_overlap, window=mlab.window_hanning, label=baseFileName1)
except KeyError:
axarr[1, 0].psd(data1[Yold], NFFT=n_samples, Fs=fs, noverlap=n_overlap, window=mlab.window_hanning, label=baseFileName1)
try:
axarr[1, 0].psd(data2[Ynew], NFFT=n_samples, Fs=fs, noverlap=n_overlap, window=mlab.window_hanning, label=baseFileName2)
except (UnboundLocalError, NameError):
pass
except KeyError:
axarr[1, 0].psd(data2[Yold], NFFT=n_samples, Fs=fs, noverlap=n_overlap, window=mlab.window_hanning, label=baseFileName2)
try:
axarr[1, 0].psd(data3[Ynew], NFFT=n_samples, Fs=fs, noverlap=n_overlap, window=mlab.window_hanning, label=baseFileName3)
except (UnboundLocalError, NameError):
pass
except KeyError:
axarr[1, 0].psd(data3[Yold], NFFT=n_samples, Fs=fs, noverlap=n_overlap, window=mlab.window_hanning, label=baseFileName3)
And here's where it got weird. When I run the thing, it throws an UnboundLocalError telling me that 'NameError' is referenced before assignment. So that except block that's supposed to catch the UnboundLocalError isn't passing like I would expect. If I try to catch just the UnboundLocalError, a NameError is thrown. If I try to catch just a NameError, an UnboundLocalError is thrown. Can somebody explain to me what's going on here?
EDIT- Here's the traceback: