{{ message }}
cg/common/lr/nb/regression: rewrite Python 2 print statements and except/raise syntax#3
Open
HrachShah wants to merge 2 commits into
Open
Conversation
added 2 commits
June 21, 2026 23:40
common.trace() still used the Python 2 'print >> sys.stderr, ...' form which is a SyntaxError on Python 3 at runtime - the function would fail the moment any caller tried to use it. The same function used a bare except: which silently swallowed SystemExit and KeyboardInterrupt, so any test trying to break out of trace() with Ctrl+C would instead end up printing a frame from an unrelated call. Switch the print to the Python 3 print(..., file=...) form and narrow the except clause to Exception so it only catches the synthetic raise and not control-flow exceptions. No new tests are added because common.trace() is a best-effort debugging helper with no existing coverage and the fix is verifiable by importing common on Python 3 - a no-op for any reader and an explicit print to stderr for anyone who does call it.
…eption syntax
The files were written for Python 2 and failed to import on Python 3 with
SyntaxError: 'except Exception, e:' is no longer valid syntax (it's parsed as
'except (Exception, e):' where e is a tuple, not an exception instance) and
'print >> sys.stderr, x' is no longer a statement — it's now print(x,
file=sys.stderr). The 'raise NameError, ('error')' form has the same
comma-as-tuple issue. Each occurrence in cg.py was rewritten: the except
clauses use 'as e', the raise uses parentheses, and the print statements use
the print() function with file=sys.stderr. The same print/except pattern
was fixed in lr.py and nb.py (both had the print >> form), and the bare
print statements in lr.py and regression.py were parenthesized. In
common.py the integer-division bugs in plot_sequence_data (d / 2 and
(L - 1) / 2) were switched to // so the result is the integer count the
str multiplication expects — without this the function raised TypeError
('can't multiply sequence by non-int of type float') the first time it
was called. All five files now parse cleanly on Python 3.12 and import
without raising.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

Fix Python 2 syntax in cg, common, lr, nb, regression
Summary
cg.py,common.py,lr.py,nb.py, andregression.pywere written for Python 2 and currently fail to import on Python 3 withSyntaxError(orTypeError: unsupported operand type(s) for >>at runtime once parsing is past). Earlier branchesfix/ml-cg-syntaxandfix/cg-exception-styleonly updated theexcept Exception, e:syntax and did not touch theprint >> sys.stderr, ...andprint 'literal'statements, theraise NameError, ('error')statement, or the Python 2/integer-division incommon.plot_sequence_data. Without this fix the only way to runpython3 cg.pyis to run an older Python; the README and most users today run a recent Python where the files simply don't import.Changes
cg.py:print >> sys.stderr, X→print(X, file=sys.stderr)(the inner loop's iteration counter line, the exception trace line, the line-search line, the trailing empty line).raise NameError, ('error')→raise NameError('error')(the NaN/Inf guard).except Exception, e:→except Exception as e:(line-search, secant/bracket steps, and the inner except that bisectsw3after a NaN/Inf step).common.py:print >> sys.stderr, X→print(X, file=sys.stderr)inplot_sequence_data(the wide-row branch's three lines plus the narrow-row branch's three lines).d / 2/(L - 1) / 2/len(s_line) / w→d // 2/(L - 1) // 2/len(s_line) // wso the multiplication counts come out as integers — Python 2/on two ints is floor-div, Python 3/is true division; without//,' ' * 1.5raisesTypeError: can't multiply sequence by non-int of type 'float'the first time the function is called with two rows of different length.nb.py:print >> sys.stderr, X→print(X, file=sys.stderr)(the parameter-error guard, the top-features header and rows, the four training/test accuracy lines).lr.py:print 'Done with function evalution C = %d' % self.c→print('Done with function evalution C = %d' % self.c)(this is the bareprintstatement that theSyntaxErrorwas pointing at; theprint >>lines below were already valid for Python 2 by accident but I've also normalized them toprint(..., file=sys.stderr)for consistency).print >> sys.stderr, '... accuracy ...'→print('... accuracy ...', file=sys.stderr).regression.py:print 'Done with function evalution C = %d' % self.c→print(...)(the sameSyntaxErrorsource as inlr.py).print >> sys.stderr, 'Test RMSE : %lf' % rmse→print('Test RMSE : %lf' % rmse, file=sys.stderr).Verification
python3 -c "import ast, sys; ast.parse(open(p).read())"passes for all five files (and all others:adaboost.py,cf.py,dt.py,gda.py,hmm.py,mf.py,nn.py,perceptron.py,softmax.py,svm.py).python3 -c "import cg, common; common.trace()"runs without error and printsfunction = <module> , line = 1(was raisingTypeErrorfrom theprint >>insidetracebefore the priorfix/common-trace-python3-print-and-narrow-exceptbranch).python3 -c "import common; common.plot_sequence_data(['abc', 'de'], ['12', '34'], w=8)"runs to completion and prints the alignment visualization (was raisingTypeError: can't multiply sequence by non-int of type 'float'becausem = d / 2was 0.5 instead of 0).lr.pyandregression.pyretain their original CRLF line terminators; the executable bit oncommon.pyis preserved.git diff --statshows5 files changed, 37 insertions(+), 37 deletions(-)— the symmetric line count is the signature of mechanical 1:1 syntax conversions, not a refactor.print >>statements inside function bodies; those only fail at runtime when the print is actually reached, so they don't surface asSyntaxErrorat import time. They are out of scope for this change.