[Tutor] Debugging in Python

John Wong gokoproject at gmail.com
Mon Nov 16 17:33:00 EST 2015


On Mon, Nov 16, 2015 at 12:48 PM, Alan Gauld <alan.gauld at btinternet.com>
wrote:
>
>
> The correct fix is to exit() from the python3 shell and start it again.
>>
>
> He's tried that and didn't find it satisfactory. That's why
> he wants a "better" workflow.
>
> Alternatively, add some main code at the end of your file and use
>> `python3 hlibert.py`:
>>
>> if __name__ == '__main__':
>>      hilbert(3)
>>
>
> That depends on the nature of his module and the type of testing he wants
> to do. He could, I agree, create a new test file that imports hilbert and
> then add his test code there but that loses the interactivity of a shell
> prompt which may be important.


Yeah, the only way you can actually keep trying is to write some kind of
test script. It doesn't have to be using any testing library. i.e. whatever
code you throw at the console for testing can be written down in another
python file. I call that a scratch pad. Obviously a proper test is
desirable. I too recommend investing time in that.

Doesn't matter whether you use a scratch pad or not, you can use PDB as
your debugger. I often use it to step into my code and hold on the
execution. I often do this when I need to inspect what an object instance
can do...

for example:

main.py

def main():
    import pdb; pdb.set_trace()
    file_object = some_complex_code_written_by_someone_else()
    do_stuff_with_file_object(file_object)

main()


Now when I run main.py, I get an interpreter session inside the PDB
debugger (it's similar to GDB if you have written C/C++ code). I can now
type  dir(file_object), play with file_object, or step inside code to
inspect errors. Hope this helps.

Thanks.

John


More information about the Tutor mailing list