Fix missing import for _ and other code improvements.

Other code improvements include:
 - more pythonic code style
 - fix pep8 warnings