Appendix A Debugging 附录 A 调试
本页译自 Think Python 2e(Allen B. Downey)· Appendix A Debugging。代码块保留英文原文不翻译;正文段段对照,中文块可用右下角按钮隐藏。
Different kinds of errors can occur in a program, and it is useful to distinguish among them in order to track them down more quickly:
- Syntax errors are produced by Python when it is translating the source code into byte code. They usually indicate that there is something wrong with the syntax of the program. Example: Omitting the colon at the end of a
defstatement yields the somewhat redundant messagedef000005 . - Runtime errors are produced by the interpreter if something goes wrong while the program is running. Most runtime error messages include information about where the error occurred and what functions were executing. Example: An infinite recursion eventually causes the runtime error “maximum recursion depth exceeded.”
- Semantic errors are problems with a program that runs without producing error messages but doesn’t do the right thing. Example: An expression may not be evaluated in the order you expect, yielding an incorrect result.
- 语法错误(syntax error)是 Python 把源代码翻译成字节码时产生的,通常表示程序的语法有问题。例如:在
def语句末尾漏写冒号,会得到一条有点多余的报错def000007 。 - 运行时错误(runtime error)是程序运行期间出错时由解释器产生的。大多数运行时错误消息会说明错误发生的位置以及当时正在执行哪些函数。例如:无限递归(infinite recursion)最终会引发运行时错误 “maximum recursion depth exceeded”(超出最大递归深度)。
- 语义错误(semantic error)指程序能运行、不报错,却没做对的事。例如:表达式的求值顺序可能和你预期的不一样,于是得到一个错误结果。
The first step in debugging is to figure out which kind of error you are dealing with. Although the following sections are organized by error type, some techniques are applicable in more than one situation.
A.1 Syntax errors A.1 语法错误
Syntax errors are usually easy to fix once you figure out what they are. Unfortunately, the error messages are often not helpful. The most common messages are def000008 and def000009 , neither of which is very informative.
def000010 (语法无效)和 def000011 (字符无效),都说不到点子上。On the other hand, the message does tell you where in the program the problem occurred. Actually, it tells you where Python noticed a problem, which is not necessarily where the error is. Sometimes the error is prior to the location of the error message, often on the preceding line.
If you are building the program incrementally, you should have a good idea about where the error is. It will be in the last line you added.
If you are copying code from a book, start by comparing your code to the book’s code very carefully. Check every character. At the same time, remember that the book might be wrong, so if you see something that looks like a syntax error, it might be.
Here are some ways to avoid the most common syntax errors:
- Make sure you are not using a Python keyword for a variable name.
- Check that you have a colon at the end of the header of every compound statement, including
def,def00,if, anddefstatements. - Make sure that any strings in the code have matching quotation marks.
- If you have multiline strings with triple quotes (single or double), make sure you have terminated the string properly. An unterminated string may cause an
def000016 error at the end of your program, or it may treat the following part of the program as a string until it comes to the next string. In the second case, it might not produce an error message at all! - An unclosed opening operator—
(,(, or(—makes Python continue with the next line as part of the current statement. Generally, an error occurs almost immediately in the next line. - Check for the classic
(instead ofifinside a conditional. - Check the indentation to make sure it lines up the way it is supposed to. Python can handle space and tabs, but if you mix them it can cause problems. The best way to avoid this problem is to use a text editor that knows about Python and generates consistent indentation.
- 确认没有拿 Python 关键字当变量名。
- 检查每个复合语句的头部末尾都有冒号,包括
def、def00、if和def语句。 - 确认代码里的字符串都有成对的引号。
- 如果你用了三引号(单或双)的多行字符串,确认字符串正确闭合。未闭合的字符串可能在程序末尾引发
def000026 错误,也可能把后面一段程序当字符串处理,直到遇见下一个字符串。第二种情况下,它可能根本不报错! - 没闭合的左括号——
(、(或(——会让 Python 把下一行继续当作当前语句的一部分。通常下一行就会立刻报错。 - 检查条件判断里有没有把经典的
if误写成(。 - 检查缩进,确保对齐正确。Python 空格和制表符都能处理,但混用会出问题。最好的办法是用一个懂 Python 的编辑器,由它生成一致的缩进。
If nothing works, move on to the next section...
A.1.1 I keep making changes and it makes no difference. A.1.1 我不断改代码,却毫无变化
If the interpreter says there is an error and you don’t see it, that might be because you and the interpreter are not looking at the same code. Check your programming environment to make sure that the program you are editing is the one Python is trying to run.
If you are not sure, try putting an obvious and deliberate syntax error at the beginning of the program. Now run it again. If the interpreter doesn’t find the new error, you are not running the new code.
There are a few likely culprits:
- You edited the file and forgot to save the changes before running it again. Some programming environments do this for you, but some don’t.
- You changed the name of the file, but you are still running the old name.
- Something in your development environment is configured incorrectly.
- If you are writing a module and using
def000, make sure you don’t give your module the same name as one of the standard Python modules. - If you are using
def000 to read a module, remember that you have to restart the interpreter or usedef000 to read a modified file. If you import the module again, it doesn’t do anything.
- 你改了文件,却忘了在重跑前保存。有些开发环境会帮你存,有些不会。
- 你改了文件名,却还在用旧名字运行。
- 你的开发环境里有某项配置错了。
- 如果你在写模块并用
def000,注意别给模块起和标准 Python 模块相同的名字。 - 如果你用
def000 载入模块,记住:要读到修改后的文件,必须重启解释器或用def000。再 import 一次并不会有任何效果。
If you get stuck and you can’t figure out what is going on, one approach is to start again with a new program like “Hello, World!,” and make sure you can get a known program to run. Then gradually add the pieces of the original program to the new one.
A.2 Runtime errors A.2 运行时错误
Once your program is syntactically correct, Python can compile it and at least start running it. What could possibly go wrong?
A.2.1 My program does absolutely nothing. A.2.1 我的程序什么都没做
This problem is most common when your file consists of functions and classes but does not actually invoke anything to start execution. This may be intentional if you only plan to import this module to supply classes and functions.
If it is not intentional, make sure that you are invoking a function to start execution, or execute one from the interactive prompt. Also see the “Flow of Execution” section below.
A.2.2 My program hangs. A.2.2 我的程序卡死了
If a program stops and seems to be doing nothing, it is “hanging.” Often that means that it is caught in an infinite loop or infinite recursion.
- If there is a particular loop that you suspect is the problem, add a
def00 statement immediately before the loop that says “entering the loop” and another immediately after that says “exiting the loop.” Run the program. If you get the first message and not the second, you’ve got an infinite loop. Go to the “Infinite Loop” section below. - Most of the time, an infinite recursion will cause the program to run for a while and then produce a “RuntimeError: Maximum recursion depth exceeded” error. If that happens, go to the “Infinite Recursion” section below. If you are not getting this error but you suspect there is a problem with a recursive method or function, you can still use the techniques in the “Infinite Recursion” section.
- If neither of those steps works, start testing other loops and other recursive functions and methods.
- If that doesn’t work, then it is possible that you don’t understand the flow of execution in your program. Go to the “Flow of Execution” section below.
- 如果你怀疑某个具体循环是祸根,在循环前加一条打印 “entering the loop”(进入循环)的
def00 语句,循环后立刻再加一条 “exiting the loop”(退出循环)。运行程序。如果只看到第一条、没看到第二条,那就是无限循环。翻到下面的「无限循环」一节。 - 多数情况下,无限递归会让程序跑一阵子,然后抛出 “RuntimeError: Maximum recursion depth exceeded”(超出最大递归深度)错误。若是如此,翻到下面的「无限递归」一节。即便没看到这个错误,但怀疑某个递归方法或函数有问题,也照样能用「无限递归」一节里的技巧。
- 如果上面两步都不管用,就去测别的循环和其他递归函数、方法。
- 如果还不行,也许是你没搞懂程序的执行流程。翻到下面的「执行流程」一节。
Infinite Loop 无限循环
If you think you have an infinite loop and you think you know what loop is causing the problem, add a def00 statement at the end of the loop that prints the values of the variables in the condition and the value of the condition.
def00 语句,打印出条件中各变量的值以及条件本身的值。For example:
def000042
Now when you run the program, you will see three lines of output for each time through the loop. The last time through the loop, the condition should be def00. If the loop keeps going, you will be able to see the values of ( and (, and you might figure out why they are not being updated correctly.
def00。如果循环还在继续,你就能看到 ( 和 ( 的值,也许能想通为什么它们没被正确更新。Infinite Recursion 无限递归
Most of the time, an infinite recursion will cause the program to run for a while and then produce a def000049 error.
def000050 (超出最大递归深度)错误。If you suspect that a function or method is causing an infinite recursion, start by checking to make sure that there is a base case. In other words, there should be some condition that will cause the function or method to return without making a recursive invocation. If not, then you need to rethink the algorithm and identify a base case.
If there is a base case but the program doesn’t seem to be reaching it, add a def00 statement at the beginning of the function or method that prints the parameters. Now when you run the program, you will see a few lines of output every time the function or method is invoked, and you will see the parameters. If the parameters are not moving toward the base case, you will get some ideas about why not.
def00 语句。运行后,函数或方法每次被调用你都会看到几行输出,也能看到参数。如果参数没有朝基础情形推进,你就能琢磨出原因了。Flow of Execution 执行流程
If you are not sure how the flow of execution is moving through your program, add def00 statements to the beginning of each function with a message like “entering function def,” where def is the name of the function.
def00 语句,打印诸如 “entering function def”(进入函数 foo)之类的信息,其中 def 是函数名。Now when you run the program, it will print a trace of each function as it is invoked.
A.2.3 When I run the program I get an exception. A.2.3 一运行程序就出现异常
If something goes wrong during runtime, Python prints a message that includes the name of the exception, the line of the program where the problem occurred, and a traceback.
The traceback identifies the function that is currently running, and then the function that invoked it, and then the function that invoked that, and so on. In other words, it traces the sequence of function invocations that got you to where you are. It also includes the line number in your file where each of these calls occurs.
The first step is to examine the place in the program where the error occurred and see if you can figure out what happened. These are some of the most common runtime errors:
- NameError:
- You are trying to use a variable that doesn’t exist in the current environment. Remember that local variables are local. You cannot refer to them from outside the function where they are defined.
- TypeError:
-
There are several possible causes:
- You are trying to use a value improperly. Example: indexing a string, list, or tuple with something other than an integer.
- There is a mismatch between the items in a format string and the items passed for conversion. This can happen if either the number of items does not match or an invalid conversion is called for.
- You are passing the wrong number of arguments to a function or method. For methods, look at the method definition and check that the first parameter is
def0. Then look at the method invocation; make sure you are invoking the method on an object with the right type and providing the other arguments correctly.
- KeyError:
- You are trying to access an element of a dictionary using a key that the dictionary does not contain.
- AttributeError:
-
You are trying to access an attribute or method that does not exist. Check the spelling! You can use
defto list the attributes that do exist. If an AttributeError indicates that an object hasdef00006, that means that it isdef0. One common cause is forgetting to return a value from a function; if you get to the end of a function without hitting adef000 statement, it returnsdef0. Another common cause is using the result from a list method, likedef0, that returnsdef0. - IndexError:
-
The index you are using to access a list, string, or tuple is greater than its length minus one. Immediately before the site of the error, add a
def00 statement to display the value of the index and the length of the array. Is the array the right size? Is the index the right value?
- NameError(名称错误):
- 你想使用一个在当前环境里不存在的变量。记住局部变量就是局部的,不能在定义它的函数之外引用。
- TypeError(类型错误):
-
可能的原因有好几种:
- 你用值的方式不对。例如:用非整数去给字符串、列表或元组做索引。
- 格式化字符串里的项和传入用于转换的项对不上。项的数量不匹配,或要求的转换方式不合法,都会这样。
- 你传给函数或方法的实参数量不对。对于方法,去看方法定义,确认第一个形参是
def0;再看方法调用,确认你是在类型正确的对象上调用该方法,并且正确地提供了其他实参。
- KeyError(键错误):
- 你想用字典里没有的键去访问字典元素。
- AttributeError(属性错误):
-
你想访问一个不存在的属性或方法。检查拼写!你可以用
def列出确实存在的属性。如果 AttributeError 提示某个对象是def00007,意思是它就是def0。一个常见原因是忘了从函数返回值:如果函数一路走到结尾都没碰上def000 语句,它就会返回def0。另一个常见原因是用了列表方法(如def0)的返回值,而它返回的是def0。 - IndexError(索引错误):
-
你用来访问列表、字符串或元组的索引,大于其长度减一。在出错位置前紧挨着加一条
def00 语句,显示出索引的值和数组的长度。数组大小对吗?索引值对吗?
The Python debugger (def) is useful for tracking down Exceptions because it allows you to examine the state of the program immediately before the error. You can read about def at def000079 .
def)对追查异常很有用,因为它能让你在出错前一刻查看程序状态。关于 def 的资料见 def000082 。A.2.4 I added so many def00 statements I get inundated with output. A.2.4 我加了太多 print 语句,被输出淹没了
One of the problems with using def00 statements for debugging is that you can end up buried in output. There are two ways to proceed: simplify the output or simplify the program.
def00 语句调试的一大问题是,你最终会被输出淹没。两条出路:简化输出,或简化程序。To simplify the output, you can remove or comment out def00 statements that aren’t helping, or combine them, or format the output so it is easier to understand.
def00 语句删掉或注释掉,或者合并它们,或者把输出格式化得更好懂。To simplify the program, there are several things you can do. First, scale down the problem the program is working on. For example, if you are searching a list, search a small list. If the program takes input from the user, give it the simplest input that causes the problem.
Second, clean up the program. Remove dead code and reorganize the program to make it as easy to read as possible. For example, if you suspect that the problem is in a deeply nested part of the program, try rewriting that part with simpler structure. If you suspect a large function, try splitting it into smaller functions and testing them separately.
Often the process of finding the minimal test case leads you to the bug. If you find that a program works in one situation but not in another, that gives you a clue about what is going on.
Similarly, rewriting a piece of code can help you find subtle bugs. If you make a change that you think shouldn’t affect the program, and it does, that can tip you off.
A.3 Semantic errors A.3 语义错误
In some ways, semantic errors are the hardest to debug, because the interpreter provides no information about what is wrong. Only you know what the program is supposed to do.
The first step is to make a connection between the program text and the behavior you are seeing. You need a hypothesis about what the program is actually doing. One of the things that makes that hard is that computers run so fast.
You will often wish that you could slow the program down to human speed, and with some debuggers you can. But the time it takes to insert a few well-placed def00 statements is often short compared to setting up the debugger, inserting and removing breakpoints, and “stepping” the program to where the error is occurring.
def00 语句,往往比搭好调试器、增删断点、再一步步「step」到出错位置要快得多。A.3.1 My program doesn’t work. A.3.1 我的程序不工作
You should ask yourself these questions:
- Is there something the program was supposed to do but which doesn’t seem to be happening? Find the section of the code that performs that function and make sure it is executing when you think it should.
- Is something happening that shouldn’t? Find code in your program that performs that function and see if it is executing when it shouldn’t.
- Is a section of code producing an effect that is not what you expected? Make sure that you understand the code in question, especially if it involves invocations to functions or methods in other Python modules. Read the documentation for the functions you invoke. Try them out by writing simple test cases and checking the results.
- 有没有程序本该做、却似乎没做的事?找到负责那项功能的代码段,确认它在你认为该执行的时候确实执行了。
- 有没有不该发生的事却发生了?找到程序里负责那项功能的代码,看看它是不是在不该执行的时候执行了。
- 有没有某段代码产生的结果和你预期的不一样?务必弄懂那段代码,尤其是当它调用了其他 Python 模块里的函数或方法时。去读你调用的函数的文档,自己写几个简单测试用例跑跑、核对结果。
In order to program, you need to have a mental model of how programs work. If you write a program that doesn’t do what you expect, very often the problem is not in the program; it’s in your mental model.
The best way to correct your mental model is to break the program into its components (usually the functions and methods) and test each component independently. Once you find the discrepancy between your model and reality, you can solve the problem.
Of course, you should be building and testing components as you develop the program. If you encounter a problem, there should be only a small amount of new code that is not known to be correct.
A.3.2 I’ve got a big hairy expression and it doesn’t do what I expect. A.3.2 我有个又大又乱的表达式,却没按预期工作
Writing complex expressions is fine as long as they are readable, but they can be hard to debug. It is often a good idea to break a complex expression into a series of assignments to temporary variables.
For example:
def000090
This can be rewritten as:
def000091
The explicit version is easier to read because the variable names provide additional documentation, and it is easier to debug because you can check the types of the intermediate variables and display their values.
Another problem that can occur with big expressions is that the order of evaluation may not be what you expect. For example, if you are translating the expression x/2 π into Python, you might write:
def000092
That is not correct because multiplication and division have the same precedence and are evaluated from left to right. So this expression computes x π / 2.
A good way to debug expressions is to add parentheses to make the order of evaluation explicit:
def000093
Whenever you are not sure of the order of evaluation, use parentheses. Not only will the program be correct (in the sense of doing what you intended), it will also be more readable for other people who haven’t memorized the rules of precedence.
A.3.3 I’ve got a function or method that doesn’t return what I expect. A.3.3 我有个函数或方法,返回值不是我预期的
If you have a def000 statement with a complex expression, you don’t have a chance to print the def000 value before returning. Again, you can use a temporary variable. For example, instead of:
def000 语句带的是一个复杂表达式,你就没机会在返回前打印 def000 值。这时照样可以用临时变量。例如,不要写:def000098
you could write:
def000099
Now you have the opportunity to display the value of def00 before returning.
def00 的值了。A.3.4 I’m really, really stuck and I need help. A.3.4 我真的、真的卡住了,需要帮忙
First, try getting away from the computer for a few minutes. Computers emit waves that affect the brain, causing these symptoms:
- Frustration and rage.
- Superstitious beliefs (“the computer hates me”) and magical thinking (“the program only works when I wear my hat backward”).
- Random walk programming (the attempt to program by writing every possible program and choosing the one that does the right thing).
- 沮丧与暴怒。
- 迷信(「计算机讨厌我」)和魔法思维(「我把帽子反着戴程序才跑得通」)。
- 随机游走式编程(试图把所有可能的程序都写一遍,再挑出那个能跑对的)。
If you find yourself suffering from any of these symptoms, get up and go for a walk. When you are calm, think about the program. What is it doing? What are some possible causes of that behavior? When was the last time you had a working program, and what did you do next?
Sometimes it just takes time to find a bug. I often find bugs when I am away from the computer and let my mind wander. Some of the best places to find bugs are trains, showers, and in bed, just before you fall asleep.
A.3.5 No, I really need help. A.3.5 不,我真的需要帮忙
It happens. Even the best programmers occasionally get stuck. Sometimes you work on a program so long that you can’t see the error. A fresh pair of eyes is just the thing.
Before you bring someone else in, make sure you are prepared. Your program should be as simple as possible, and you should be working on the smallest input that causes the error. You should have def00 statements in the appropriate places (and the output they produce should be comprehensible). You should understand the problem well enough to describe it concisely.
def00 的地方要加上(而且它产生的输出要能看得懂)。你要对问题理解到能简洁描述它的程度。When you bring someone in to help, be sure to give them the information they need:
- If there is an error message, what is it and what part of the program does it indicate?
- What was the last thing you did before this error occurred? What were the last lines of code that you wrote, or what is the new test case that fails?
- What have you tried so far, and what have you learned?
- 如果有错误消息,它是什么,又指向程序的哪一部分?
- 出错前你最后做了什么?你最后写的几行代码是什么,或者新失败的测试用例是什么?
- 你到目前为止试过哪些办法,又学到了什么?
When you find the bug, take a second to think about what you could have done to find it faster. Next time you see something similar, you will be able to find the bug more quickly.
Remember, the goal is not just to make the program work. The goal is to learn how to make the program work.