License Creative Commons Attribution Non-Commercial Share Alike 3.0-US
Keywords
console (1) debug (6) reload (1)
Permissions
Group Owner: iCapsid
Viewable by Everyone
Editable by All Siafoo Users

Python Debugging Tips Atom Feed 0

Learn the best ways to debug your Python code, or share tips that you've learned. Too lazy to write something? That's cool... at least give us some ideas at the bottom : )

Feel free to edit this article! I'd like to compile some good tips about debugging in Python... I'm honestly not that efficient and I'd like to hear your ideas.

1   Should I Use the Console?

1.1   The Console is Dead

If you need to write a function or class that's more complicated than a few lines, don't bother doing it on the interactive console. Why? Because you'll inevitably make a mistake somewhere. And then you'll have to start over. I know that you can just hammer 'up' to re-type earlier lines, but it's a pain. Your indentation will be messed up somehow too.

1.2   Long Live the Console!

The console is also one of the best things about Python. Because Python is an interpreted language, you can come up with quick examples to test whatever you need to. You can perform introspection on the fly. You can call functions and see what gets printed or returned.

So should you use the console? Yes, definitely, but don't write long classes and functions in it... make a quick test.py file, start the console in that directory, and import it. Change the file and reload it.

2   Reload a Module

The simplest debugging tip I can think of is the builtin reload function. You're aware, hopefully, that import loads a module from somewhere in the search path. For efficiency, though, import-ing the same file again won't do anything; why should Python load code that's already loaded?

The solution is to reload the module. You just need to call reload(module):

1>>> import test
2>>> test.answer_to_life_the_universe_and_everything
354
4>>> # Whoops that's not right, I'd better edit the module....
5...
6>>> reload(test)
7>>> test.answer_to_life_the_universe_and_everything
842

Warning

You can only reload a module that has been import-ed as a whole -- if you do a "from ... import ..." and then reload the module, the imported object will not be updated. [1]

There are a number of caveats, few of which you are likely to run into. But if things aren't behaving the way you expect, you might want to give them a look.

3   More Ideas

Obviously trace and ctrace should be talked about in this article. What else?

[1]The reload docs mention that you should just be able to do the "from ... import ..." statement again, but that doesn't seem to actually work. Anyone know if there's any way to do this?