Wednesday, 29 January 2014

Pdb ftw

pdb - python debugger

If a script throws an exception, try running it in the debugger
python -m pdb myscript.py
For example given the following (rubbish) python program
C:\Dev\src>cat bad.py
def naughty():
 raise Exception()
naughty()

if we just run it the exception tries to escape ...
C:\Dev\src>python bad.py
Traceback (most recent call last):
 File "bad.py", line 4, in <module>
 naughty()
 File "bad.py", line 2, in naughty
 raise Exception()
Exception

So, we know what line the problem's on. We could change the script to see what's going on using
import pdb; pdb.set_trace()
or we could run it under a debugger.

Run script through debugger

Invoke the pdb module in python and send it your script, e.g.
python -m pdb bad.py
This gives a (Pdb) prompt to type instructions in to:
> c:\dev\src\bad.py(1)<module>()
-> def naughty():
(Pdb)
Type 'c' for continue - it will halt when it gets an exception, as follows
(Pdb) c
Traceback (most recent call last):
 File "C:\Python27\lib\pdb.py", line 1314, in main
 pdb._runscript(mainpyfile)
 File "C:\Python27\lib\pdb.py", line 1233, in _runscript
 self.run(statement)
 File "C:\Python27\lib\bdb.py", line 387, in run
 exec cmd in globals, locals
 File "<string>", line 1, in <module>
 File "bad.py", line 1, in <module>
 def naughty():
 File "bad.py", line 2, in naughty
 raise Exception()
Exception
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
> c:\dev\src\bad.py(2)naughty()
-> raise Exception()
(Pdb)
At this point
 (Pdb) p <variable_name>
can be used to inspect variables, and
 (Pdb) a
shows any arguments to a function.

Main Pdb commands

Type 'q' for quit, 's' to step (maybe into another function) or 'n' to move on to the next line.
'w' shows where you are in the stack, 'u' moves up and 'd' moves down.
b(reak) [[filename:]lineno  sets a breakpoint.
There are more details in the manual: http://docs.python.org/2/library/pdb.html

Tuesday, 21 January 2014

Virtual functions in constructors and destructors

Interview question.

What does this do?

class Base
{
public:
Base()
{
log();
}
virtual ~Base()
{
log();
}

//virtual void log() = 0;//note this compiles but doesn't link
virtual void log()
{
std::cout << "Base\n";
}
};

class Derived : public Base
{
public:
Derived()
{
log();
}
~Derived()
{
log();
}
virtual void log()
{
std::cout << "Derived\n";
}
};

int main()
{
Derived d;
}

I half remembered this http://www.artima.com/cppsource/nevercall.html so wasn't sure.