cg/common/lr/nb/regression: rewrite Python 2 print statements and except/raise syntax by HrachShah · Pull Request #3 · mazefeng/ml · GitHub
Skip to content

cg/common/lr/nb/regression: rewrite Python 2 print statements and except/raise syntax#3

Open
HrachShah wants to merge 2 commits into
mazefeng:masterfrom
HrachShah:fix/cg-py2-raise-except-print-syntax
Open

cg/common/lr/nb/regression: rewrite Python 2 print statements and except/raise syntax#3
HrachShah wants to merge 2 commits into
mazefeng:masterfrom
HrachShah:fix/cg-py2-raise-except-print-syntax

Conversation

@HrachShah

Copy link
Copy Markdown

Fix Python 2 syntax in cg, common, lr, nb, regression

Summary

cg.py, common.py, lr.py, nb.py, and regression.py were written for Python 2 and currently fail to import on Python 3 with SyntaxError (or TypeError: unsupported operand type(s) for >> at runtime once parsing is past). Earlier branches fix/ml-cg-syntax and fix/cg-exception-style only updated the except Exception, e: syntax and did not touch the print >> sys.stderr, ... and print 'literal' statements, the raise NameError, ('error') statement, or the Python 2 / integer-division in common.plot_sequence_data. Without this fix the only way to run python3 cg.py is 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, Xprint(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 bisects w3 after a NaN/Inf step).

common.py:

  • print >> sys.stderr, Xprint(X, file=sys.stderr) in plot_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) / wd // 2 / (L - 1) // 2 / len(s_line) // w so the multiplication counts come out as integers — Python 2 / on two ints is floor-div, Python 3 / is true division; without //, ' ' * 1.5 raises TypeError: 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, Xprint(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.cprint('Done with function evalution C = %d' % self.c) (this is the bare print statement that the SyntaxError was pointing at; the print >> lines below were already valid for Python 2 by accident but I've also normalized them to print(..., file=sys.stderr) for consistency).
  • print >> sys.stderr, '... accuracy ...'print('... accuracy ...', file=sys.stderr).

regression.py:

  • print 'Done with function evalution C = %d' % self.cprint(...) (the same SyntaxError source as in lr.py).
  • print >> sys.stderr, 'Test RMSE : %lf' % rmseprint('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 prints function = <module> , line = 1 (was raising TypeError from the print >> inside trace before the prior fix/common-trace-python3-print-and-narrow-except branch).
  • python3 -c "import common; common.plot_sequence_data(['abc', 'de'], ['12', '34'], w=8)" runs to completion and prints the alignment visualization (was raising TypeError: can't multiply sequence by non-int of type 'float' because m = d / 2 was 0.5 instead of 0).
  • Line endings preserved: lr.py and regression.py retain their original CRLF line terminators; the executable bit on common.py is preserved. git diff --stat shows 5 files changed, 37 insertions(+), 37 deletions(-) — the symmetric line count is the signature of mechanical 1:1 syntax conversions, not a refactor.
  • The other algorithmic files (adaboost, cf, dt, gda, hmm, mf, nn, perceptron, softmax, svm) all still have Python 2 print >> statements inside function bodies; those only fail at runtime when the print is actually reached, so they don't surface as SyntaxError at import time. They are out of scope for this change.

Zo Bot 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant