[Tutor] A question about daunting KeyError
Steven D'Aprano
steve at pearwood.info
Wed Jul 24 04:37:10 EDT 2019
Hi Taishi, and welcome.
On Wed, Jul 24, 2019 at 03:21:03AM +0000, TAISHI KAWAMURA wrote:
[...]
> I'm suspecting that Anaconda might keep raising the error, or simply
> there are bugs in the codes. However, I can't be sure what the real
> cause is.
Almost certainly it will be a bug in your code, or unexpected values in
your data. It is possible that it is a bug in Anaconda, but not very
likely.
Start by removing Anaconda from the problem: what happens if you run
your code using the plain Python interpreter, without Anaconda involved?
>From the operating system command line, run something like this:
# Windows CMD.EXE
py path/to/myscript.py
# Linux or Mac OS shell
python path/to/myscript.py
Of course the example command you run will depend on the version of
Python you are using, and the name and path to your script.
If the error goes away without Anaconda involved, then it is *possible*
that it is a bug in Anaconda. But I expect the error will remain.
Then show us the full traceback of the error. Copy and paste the FULL
exception message, starting with the line "Traceback" and ending with
the KeyError and error message, something like this but probably longer:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: (1, 2, 3)
Once you know the line where the error is occurring, you could introduce
some debugging code:
try:
result = data[key]
except KeyError:
log(data)
log(key)
raise
or use the debugger to investigate why the key is missing.
You should also read this:
http://sscce.org/
It is written for Java programmers, but it applies to Python too.
--
Steven
More information about the Tutor
mailing list