Python 2 to 3 Conversion Notes

A project that I’m working on is being produced with the intention that it will be in production for a very long time — 10+ years. Thus converting from Python 2.7 to Python 3.4 seems to be a wise option to explore.

These are some personal notes regarding the differences between the two versions, supplementing the excellent articles out there. These are based on examining diffs after running 2to3 on the code base.

xrange and range

Contrary to what is implied in many articles, the separate functionality in xrange and range has not been mysteriously merged.The Python 2.7 xrange has been renamed to range. The Python 2.7 range is gone completely. To get the same effect, use


foo = list(range(1, 10))

 

The 2to3 code tool did this correctly; seeing its effect merely clarified how Python 3 works.

__unicode__

I had to manually go through my objects and straighten out __str__ and __unicode__. This involved:

  1. Deleting __str__ methods which essentially duplicated __unicode__.
  2. Renaming __unicode__ to __str__.

__long__

I used __long__ in one object, and simply deleted it since under Python 3 it is a duplicate of __int__.

long() and int()

Similar to __long__, there was one instance where I simply deleted the code associated with long().

super()

I had to manually convert the Python 2.7


super(ClassName, self)

to


super()

 map()

2to3 attempts to convert map() statements to list comprehensions. It did well on most, but screwed up in two places. It might be wise to search for leftover map() statements.

Updates

14 May 2014
Added notes for map().

 

 

Posted in Programming | Tagged , , , , , | Leave a comment

Little Schemer on OS X

I’ve joined a local study group that’s going through The Little Schemer. I learned LISP in the early ’80s but never pursued it deeply. (I certainly used Emacs, but never fully embraced it.) My purpose now is as a refresher on recursion.

For a quick useful IDE on OS X, the Dr. Racket IDE seems to fit the bill nicely. (Racket is in the LISP family.)

To use Dr. Racket, the upper portion is an editor, and when run, provides an interactive command prompt below. (Dr. Racket will probably complain about needing a language. Simply select Racket.)

To use Dr. Racket with The Little Schemer, one will need to add the definition for atom? immediately after this opening line, then run the script to bring up the command line.


#lang racket

(define atom? (lambda (x) (not (list? x))))

Also, one should note that Scheme requires literals such as atom as lists to be quoted:


(list? (quote ()))

(list? '())

(atom? (quote abc))

(atom? 'abc)

 

Posted in Programming | Tagged , , , | Leave a comment

ui-bootstrap Oddity

The <tab> element from the Angular-UI project’s ui-bootstrap has an oddity with the activate attribute, it seems, when calling a function to determine whether a tab should be active. For example,


<tab ng-repeat="u in foo.units" active="activeTab(u)">

causes JavaScript errors and the tabs do not function correctly. Poking around in the internals of ui-bootstrap-tpls.js lead to me discover that in this case the code

if (attrs.active) {
    getActive = $parse(attrs.active);
    setActive = getActive.assign;

leaves setActive to undefined. The JavaScript later attempts to call setActive, which crashes and burns of course.

I was able to work around the problem by copying the essentials of the activeTab function into the active attribute, e.g.


<tab ng-repeat="u in foo.units" active="bar.isPlugh == u.state.isPlugh">

Posted in Programming | Tagged , , , , | Leave a comment

Quick Jasmine 2 Reference

The Jasmine 2 Introduction is a wonderful combination of a demo and reference. However I’d rather not have to scroll through to find something.

Matchers

Jasmine Description Example
not Negation expect(‘foo’).not.toBe(‘bar’)
toBe() === expect(‘1′).not.toBe(1)
toEqual() Smarter check; should handle simple objects. expect(‘1′).toEqual(1)
toMatch() Regex expect(‘1′).toMatch(/\d/)
toBeDefined() !== undefined expect(1).toBeDefined()
toBeUndefined() === undefined expect().toBeUndefined()
toBeNull() === null expect(null).toBeNull()
toBeTruthy() true expect(‘1′).toBeTruthy()
toBeFalsy() false expect(”).toBeFalsy()
toContain() in array expect([1,2]).toContain(2)
toBeLessThan() < expect(1).toBeLessThan(2)
toBeGreaterThan() > expect(1).toBeGreaterThan(0)
toBeCloseTo() floating point comparison expect(2.0/2.0).toBeCloseTo(1)
toThrow() pass in function reference expect(func).toThrow()

Notes on toThrow()

toThrow() takes a function reference, which it calls with no parameters. If you need to pass parameters, you can wrap it in another function(){}.

If called with no parameters, it passes on any exception. If called with a parameter, the exception must equal the parameter.

Posted in Programming | Tagged , , , , , , , | Leave a comment

Regular Expression for Validating Floating-Point Numbers

This is more of a classroom assignment problem, but it creeps up from time to time in the real world. The best I’ve been able to come up with over the years is:


/^\s*[-+]?(\d*\.?\d+|\d+\.)(e[-+]?[0-9]+)?\s*$/i;

Why?

I was asked why bother with this when JavaScript has a parseFloat() function.

This can be useful when one must ensure that a string contains an actual floating-point number and nothing else.

The JavaScript parseFloat() function will accept any string (including garbage like alphabetic characters) so long as the first sequence of characters is a float.

The MDN page gives the following examples, all of which return 3.14:

parseFloat("3.14");
parseFloat("314e-2");
parseFloat("0.0314E+2");
parseFloat("3.14more non-digit characters");

The last example contains a string that is clearly not a valid number.

Posted in Programming | Tagged , , , , , , | Leave a comment

Set Background Colour with AngularJS

From the “I can’t believe I had to look it up” department:

One can use ngStyle to programmatically set the background colour of an element. This is arbitrary ugly code that demonstrates the concept:

<span ng-style="{background: item.color}">

The “gotcha” is if one wishes to only use this on a certain page, one must reset the colour when the controller’s $scope is destroyed:

$scope.$on("$destroy", function(){
    $("body").css('background-color', 'white');
});
Posted in Uncategorized | Leave a comment

AngularJS Directives: Expression or Interpolation?

AngularJS seems to be inconsistent on whether a directive can contain an expression or requires an expression to be wrapped in interpolation brackets {{ thusly }}.

Here is a partial list of directives consisting of ones that have bitten me.

Directive Expression or Interpolation? Notes
ng-class Expression Accepts an object, array or string.
ng-src Interpolation
ng-href Interpolation
ng-srcset Interpolation
ng-style Expression Give it an object.
ng-include Interpolation Accepts a string.
Posted in Programming | Tagged , , , | Leave a comment