In Python, omitting the trailing parentheses from the end of a method call (one that takes no arguments) is not a syntax error. The place where this most frequently bites me is with the “close” method on file objects. Suppose you have an output file called “foo” and you want to close it. The correct way to do this is:
However, if you accidentally omit the trailing parentheses, and code this:
Python will not report a syntax error, because this is not an error in Python. In Python, this is a perfectly legitimate statement that returns the method object “close”. (Remember that methods are first-class objects in Python.) If you do this in the Python interpreter, you will get a message like this:
<built-in method close of file object at 0x007E6AE0>
The nastiness about this gotcha is that if you fail to code the trailing parentheses on a “close” method for an output file, the output file will not be closed properly. The file’s output buffer will not be flushed out to disk, and the part of the output stream that was still left in the output buffer will be lost. After your program finishes, part of your output file will be missing, and you won’t know why.
The best way of dealing with this gotcha is just to be aware that it can be a problem, and to be alert. Be careful to code the parenthese on your method calls, and especially careful to code them on calls to the “close” method of file objects.
And if you find yourself with an output file that seems to be inexplicably truncated, your first thought should be to check for missing parentheses in the file.close() statement that closes the file.
Programs like PyChecker and PyLint may be able to detect this kind of error, which is one good reason to use them.