In python versions before PEP 553 breakpoint() utility, what is the recommended way to add (ideally a one-liner) code to have a breakpoint that can be ignored upon a condition (e.g. a global debug flag or args.debug flag).
In Perl, I am used to use $DB::single=1;1; single-lines, which I know I can safely leave in the code and won't affect the normal running of perl code.pl unless explicitly calling perl -d code.pl. E.g.:
my $a = 1;
$DB::single=1;1; # breakpoint line
my $b = 2;
print "$a $b\n";
If I run this code as: perl code.pl, it will run to completion.
If I run this code with: perl -d code.pl, the pdb will stop at the breakpoint line (not before the next line with a my $b = 2; statement) because it contains a 1; statement after the $DB::single=1; statement;
Similarly, if I write:
my $debug = 1;
my $a = 1;
$DB::single=$debug;1; # first breakpoint line
my $b = 2;
$DB::single=$debug;1; # second breakpoint line
print "$a $b\n";
# [...] Lots more code sprinkled with more of these
$DB::single=$debug;1; # n'th breakpoint line
I can then execute perl -d code.pl, which will stop in the first breakpoint line, then in the pdb session, once I am happy that it does not need stopping anywhere else, then execute: $debug = 0, then pdb continue c, which will make it not stop at the second or other similar breakpoint lines in the code.
How can I achieve the same, ideally in single-line statements, in python (2.x and 3.x before PEP 553)?
I am aware of PEP 553 and apart from the hassle of having to explicitly set PYTHONBREAKPOINT=0 python3.7 code.py or comment out the breakpoint() lines, it is a solution to the question here.
I thought of options like:
import pdb; pdb.set_trace()
dummy=None;
The statement underneath pdb.set_trace() is so that I can achieve the same as the 1; in the same line after $DB::single=1; in Perl, which is to have the debugger stop where I placed the breakpoint, rather than the next statement. This is so that if there are large chunks of commented code or documentation in-between, the debugger does not jump to the next statement far away from the breakpoint.
Or with conditionals like:
if args.debug or debug:
import pdb; pdb.set_trace()
_debug=False; #args.debug=False
So that if I am done debugging for a script, I can set args.debug=False or debug=False and not have to touch all these breakpoints in the code.
Here is a simple way using a
.pdbrcfile in the current directory:t.py
.pdbrc:
Example session: