svgui/pyjs/pyjs.py
changeset 1784 64beb9e9c749
parent 1783 3311eea28d56
child 1785 0ff2a45dcefa
--- a/svgui/pyjs/pyjs.py	Mon Aug 21 20:17:19 2017 +0000
+++ b/svgui/pyjs/pyjs.py	Mon Aug 21 23:22:58 2017 +0300
@@ -20,6 +20,7 @@
 from compiler import ast
 import os
 import copy
+import cStringIO
 
 # the standard location for builtins (e.g. pyjslib) can be
 # over-ridden by changing this.  it defaults to sys.prefix
@@ -31,7 +32,7 @@
 
 prefix = sys.prefix
 
-if os.environ.has_key('PYJSPREFIX'):
+if 'PYJSPREFIX' in os.environ:
     prefix = os.environ['PYJSPREFIX']
 
 # pyjs.path is the list of paths, just like sys.path, from which
@@ -41,7 +42,7 @@
 
 path = [os.path.abspath('')]
 
-if os.environ.has_key('PYJSPATH'):
+if 'PYJSPATH' in os.environ:
     for p in os.environ['PYJSPATH'].split(os.pathsep):
         p = os.path.abspath(p)
         if os.path.isdir(p):
@@ -52,43 +53,43 @@
 
 UU = ""
 
-PYJSLIB_BUILTIN_FUNCTIONS=("cmp",
-                           "map",
-                           "filter",
-                           "dir",
-                           "getattr",
-                           "setattr",
-                           "hasattr",
-                           "int",
-                           "float",
-                           "str",
-                           "repr",
-                           "range",
-                           "len",
-                           "hash",
-                           "abs",
-                           "ord",
-                           "chr",
-                           "enumerate",
-                           "min",
-                           "max",
-                           "bool",
-                           "type",
-                           "isinstance")
-
-PYJSLIB_BUILTIN_CLASSES=("BaseException",
-                         "Exception",
-                         "StandardError",
-                         "StopIteration",
-                         "AttributeError",
-                         "TypeError",
-                         "KeyError",
-                         "LookupError",
-                         "list",
-                         "dict",
-                         "object",
-                         "tuple",
-                        )
+PYJSLIB_BUILTIN_FUNCTIONS = ("cmp",
+                             "map",
+                             "filter",
+                             "dir",
+                             "getattr",
+                             "setattr",
+                             "hasattr",
+                             "int",
+                             "float",
+                             "str",
+                             "repr",
+                             "range",
+                             "len",
+                             "hash",
+                             "abs",
+                             "ord",
+                             "chr",
+                             "enumerate",
+                             "min",
+                             "max",
+                             "bool",
+                             "type",
+                             "isinstance")
+
+PYJSLIB_BUILTIN_CLASSES = ("BaseException",
+                           "Exception",
+                           "StandardError",
+                           "StopIteration",
+                           "AttributeError",
+                           "TypeError",
+                           "KeyError",
+                           "LookupError",
+                           "list",
+                           "dict",
+                           "object",
+                           "tuple")
+
 
 def pyjs_builtin_remap(name):
     # XXX HACK!
@@ -102,10 +103,11 @@
         name = 'Tuple'
     return name
 
+
 # XXX: this is a hack: these should be dealt with another way
 # however, console is currently the only global name which is causing
 # problems.
-PYJS_GLOBAL_VARS=("console")
+PYJS_GLOBAL_VARS = ("console")
 
 # This is taken from the django project.
 # Escape every ASCII character with a value less than 32.
@@ -119,17 +121,20 @@
     (';', r'\x3B')
     ) + tuple([('%c' % z, '\\x%02X' % z) for z in range(32)])
 
+
 def escapejs(value):
     """Hex encodes characters for use in JavaScript strings."""
     for bad, good in JS_ESCAPES:
         value = value.replace(bad, good)
     return value
 
+
 def uuprefix(name, leave_alone=0):
     name = name.split(".")
     name = name[:leave_alone] + map(lambda x: "__%s" % x, name[leave_alone:])
     return '.'.join(name)
 
+
 class Klass:
 
     klasses = {}
@@ -154,9 +159,11 @@
     def __str__(self):
         return self.message
 
+
 def strip_py(name):
     return name
 
+
 def mod_var_name_decl(raw_module_name):
     """ function to get the last component of the module e.g.
         pyjamas.ui.DOM into the "namespace".  i.e. doing
@@ -174,12 +181,14 @@
     child_name = name[-1]
     return "var %s = %s;\n" % (child_name, raw_module_name)
 
+
 def gen_mod_import(parentName, importName, dynamic=1):
-    #pyjs_ajax_eval("%(n)s.cache.js", null, true);
+    # pyjs_ajax_eval("%(n)s.cache.js", null, true);
     return """
     pyjslib.import_module(sys.loadpath, '%(p)s', '%(n)s', %(d)d, false);
     """ % ({'p': parentName, 'd': dynamic, 'n': importName}) + \
-    mod_var_name_decl(importName)
+        mod_var_name_decl(importName)
+
 
 class Translator:
 
@@ -228,7 +237,6 @@
         if decl:
             print >>self.output, decl
 
-
         if self.debug:
             haltException = self.module_prefix + "HaltException"
             print >>self.output, haltException + ' = function () {'
@@ -273,14 +281,14 @@
                 self._class(child)
             elif isinstance(child, ast.Import):
                 importName = child.names[0][0]
-                if importName == '__pyjamas__': # special module to help make pyjamas modules loadable in the python interpreter
+                if importName == '__pyjamas__':  # special module to help make pyjamas modules loadable in the python interpreter
                     pass
                 elif importName.endswith('.js'):
-                   self.imported_js.add(importName)
+                    self.imported_js.add(importName)
                 else:
-                   self.add_imported_module(strip_py(importName))
+                    self.add_imported_module(strip_py(importName))
             elif isinstance(child, ast.From):
-                if child.modname == '__pyjamas__': # special module to help make pyjamas modules loadable in the python interpreter
+                if child.modname == '__pyjamas__':  # special module to help make pyjamas modules loadable in the python interpreter
                     pass
                 else:
                     self.add_imported_module(child.modname)
@@ -302,9 +310,9 @@
             elif isinstance(child, ast.Global):
                 self._global(child, None)
             elif isinstance(child, ast.Printnl):
-               self._print(child, None)
+                self._print(child, None)
             elif isinstance(child, ast.Print):
-               self._print(child, None)
+                self._print(child, None)
             elif isinstance(child, ast.TryExcept):
                 self._tryExcept(child, None)
             elif isinstance(child, ast.Raise):
@@ -315,14 +323,14 @@
                 raise TranslationError("unsupported type (in __init__)", child)
 
         # Initialize all classes for this module
-        #print >> self.output, "__"+self.modpfx()+\
+        # print >> self.output, "__"+self.modpfx()+\
         #          "classes_initialize = function() {\n"
-        #for className in self.top_level_classes:
+        # for className in self.top_level_classes:
         #    print >> self.output, "\t"+UU+self.modpfx()+"__"+className+"_initialize();"
-        #print >> self.output, "};\n"
+        # print >> self.output, "};\n"
 
         print >> self.output, "return this;\n"
-        print >> self.output, "}; /* end %s */ \n"  % module_name
+        print >> self.output, "}; /* end %s */ \n" % module_name
 
     def module_imports(self):
         return self.imported_modules + self.imported_modules_as
@@ -345,7 +353,7 @@
             # added to the dependencies, and it's half way up the
             # module import directory structure!
             child_name = name[-1]
-            self.imported_modules_as.append(child_name) 
+            self.imported_modules_as.append(child_name)
         print >> self.output, gen_mod_import(self.raw_module_name,
                                              strip_py(importName),
                                              self.dynamic)
@@ -396,12 +404,13 @@
 #                    raise TranslationError("unsupported type (in _method)", default_node)
 
                 default_name = arg_names[default_pos]
-                print >>self.output, "    if (typeof %s == 'undefined')"%(default_name)
-                print >>self.output, "        %s=__kwargs.%s;"% (default_name, default_name)
+                print >>self.output, "    if (typeof %s == 'undefined')" % (default_name)
+                print >>self.output, "        %s=__kwargs.%s;" % (default_name, default_name)
                 default_pos += 1
 
-            #self._default_args_handler(node, arg_names, current_klass)
-            if node.kwargs: arg_names += ["pyjslib.Dict(__kwargs)"]
+            # self._default_args_handler(node, arg_names, current_klass)
+            if node.kwargs:
+                arg_names += ["pyjslib.Dict(__kwargs)"]
             print >>self.output, "    var __r = "+"".join(["[", ", ".join(arg_names), "]"])+";"
             if node.varargs:
                 self._varargs_handler(node, "__args", arg_names, current_klass)
@@ -418,16 +427,19 @@
 
         arg_names = list(node.argnames)
         normal_arg_names = list(arg_names)
-        if node.kwargs: kwargname = normal_arg_names.pop()
-        if node.varargs: varargname = normal_arg_names.pop()
+        if node.kwargs:
+            kwargname = normal_arg_names.pop()
+        if node.varargs:
+            varargname = normal_arg_names.pop()
         declared_arg_names = list(normal_arg_names)
-        if node.kwargs: declared_arg_names.append(kwargname)
+        if node.kwargs:
+            declared_arg_names.append(kwargname)
 
         function_args = "(" + ", ".join(declared_arg_names) + ")"
         print >>self.output, "%s = function%s {" % (function_name, function_args)
         self._default_args_handler(node, normal_arg_names, None)
 
-        local_arg_names = normal_arg_names + declared_arg_names 
+        local_arg_names = normal_arg_names + declared_arg_names
 
         if node.varargs:
             self._varargs_handler(node, varargname, declared_arg_names, None)
@@ -451,25 +463,20 @@
         print >>self.output, "};"
         print >>self.output, "%s.__name__ = '%s';\n" % (function_name, node.name)
 
-
         self._kwargs_parser(node, function_name, normal_arg_names, None)
 
-
     def _return(self, node, current_klass):
         expr = self.expr(node.value, current_klass)
         # in python a function call always returns None, so we do it
         # here too
         print >>self.output, "    return " + expr + ";"
 
-
     def _break(self, node, current_klass):
         print >>self.output, "    break;"
 
-
     def _continue(self, node, current_klass):
         print >>self.output, "    continue;"
 
-
     def _callfunc(self, v, current_klass):
 
         if isinstance(v.node, ast.Name):
@@ -477,7 +484,7 @@
                 call_name = self.modpfx() + v.node.name
             elif v.node.name in self.top_level_classes:
                 call_name = self.modpfx() + v.node.name
-            elif self.imported_classes.has_key(v.node.name):
+            elif v.node.name in self.imported_classes:
                 call_name = self.imported_classes[v.node.name] + '.' + v.node.name
             elif v.node.name in PYJSLIB_BUILTIN_FUNCTIONS:
                 call_name = 'pyjslib.' + v.node.name
@@ -535,18 +542,15 @@
         if kwargs or star_arg_name:
             if not star_arg_name:
                 star_arg_name = 'null'
-            try: call_this, method_name = call_name.rsplit(".", 1)
+            try:
+                call_this, method_name = call_name.rsplit(".", 1)
             except ValueError:
                 # Must be a function call ...
                 return ("pyjs_kwargs_function_call("+call_name+", "
-                                  + star_arg_name 
-                                  + ", ["+fn_args+"]"
-                                  + ")" )
+                        + star_arg_name + ", ["+fn_args+"]" + ")")
             else:
                 return ("pyjs_kwargs_method_call("+call_this+", '"+method_name+"', "
-                                  + star_arg_name 
-                                  + ", ["+fn_args+"]"
-                                  + ")")
+                        + star_arg_name + ", ["+fn_args+"]" + ")")
         else:
             return call_name + "(" + ", ".join(call_args) + ")"
 
@@ -581,19 +585,19 @@
             self._stmt(stmt, current_klass)
         print >> self.output, "    } catch(%s) {" % errName
         if expr:
-            l = []
+            k = []
             if isinstance(expr, ast.Tuple):
                 for x in expr.nodes:
-                    l.append("(%(err)s.__name__ == %(expr)s.__name__)" % dict (err=errName, expr=self.expr(x, current_klass)))
-            else:
-                l = [ " (%(err)s.__name__ == %(expr)s.__name__) " % dict (err=errName, expr=self.expr(expr, current_klass)) ]
-            print >> self.output, "   if(%s) {" % '||\n\t\t'.join(l)
+                    k.append("(%(err)s.__name__ == %(expr)s.__name__)" % dict(err=errName, expr=self.expr(x, current_klass)))
+            else:
+                k = [" (%(err)s.__name__ == %(expr)s.__name__) " % dict(err=errName, expr=self.expr(expr, current_klass))]
+            print >> self.output, "   if(%s) {" % '||\n\t\t'.join(k)
         for stmt in node.handlers[0][2]:
             self._stmt(stmt, current_klass)
         if expr:
-            #print >> self.output, "} else { throw(%s); } " % errName
+            # print >> self.output, "} else { throw(%s); } " % errName
             print >> self.output, "}"
-        if node.else_ != None:
+        if node.else_ is not None:
             print >>self.output, "    } finally {"
             for stmt in node.else_:
                 self._stmt(stmt, current_klass)
@@ -605,13 +609,13 @@
         attr_name = v.attrname
         if isinstance(v.expr, ast.Name):
             obj = self._name(v.expr, current_klass, return_none_for_module=True)
-            if obj == None and v.expr.name in self.module_imports():
+            if obj is None and v.expr.name in self.module_imports():
                 # XXX TODO: distinguish between module import classes
                 # and variables.  right now, this is a hack to get
                 # the sys module working.
-                #if v.expr.name == 'sys':
+                # if v.expr.name == 'sys':
                 return v.expr.name+'.'+attr_name
-                #return v.expr.name+'.__'+attr_name+'.prototype.__class__'
+                # return v.expr.name+'.__'+attr_name+'.prototype.__class__'
             if not use_getattr or attr_name == '__class__' or \
                     attr_name == '__name__':
                 return obj + "." + attr_name
@@ -625,12 +629,11 @@
         else:
             raise TranslationError("unsupported type (in _getattr)", v.expr)
 
-
     def modpfx(self):
         return strip_py(self.module_prefix)
-        
+
     def _name(self, v, current_klass, top_level=False,
-                                      return_none_for_module=False):
+              return_none_for_module=False):
 
         if v.name == 'ilikesillynamesfornicedebugcode':
             print top_level, current_klass, repr(v)
@@ -662,14 +665,14 @@
             return UU+self.modpfx() + v.name
         elif v.name in local_var_names:
             return v.name
-        elif self.imported_classes.has_key(v.name):
+        elif v.name in self.imported_classes:
             return UU+self.imported_classes[v.name] + '.__' + v.name + ".prototype.__class__"
         elif v.name in self.top_level_classes:
             return UU+self.modpfx() + "__" + v.name + ".prototype.__class__"
         elif v.name in self.module_imports() and return_none_for_module:
             return None
         elif v.name in PYJSLIB_BUILTIN_CLASSES:
-            return "pyjslib." + pyjs_builtin_remap( v.name )
+            return "pyjslib." + pyjs_builtin_remap(v.name)
         elif current_klass:
             if v.name not in local_var_names and \
                v.name not in self.top_level_vars and \
@@ -681,9 +684,8 @@
                     cls_name_ = cls_name.name_
                     cls_name = cls_name.name
                 else:
-                    cls_name_ = current_klass + "_" # XXX ???
-                name = UU+cls_name_ + ".prototype.__class__." \
-                                   + v.name
+                    cls_name_ = current_klass + "_"  # XXX ???
+                name = UU+cls_name_ + ".prototype.__class__." + v.name
                 if v.name == 'listener':
                     name = 'listener+' + name
                 return name
@@ -695,33 +697,31 @@
 
         if obj in self.method_imported_globals:
             call_name = UU+self.modpfx() + obj + "." + attr_name
-        elif self.imported_classes.has_key(obj):
-            #attr_str = ""
-            #if attr_name != "__init__":
+        elif obj in self.imported_classes:
+            # attr_str = ""
+            # if attr_name != "__init__":
             attr_str = ".prototype.__class__." + attr_name
             call_name = UU+self.imported_classes[obj] + '.__' + obj + attr_str
         elif obj in self.module_imports():
             call_name = obj + "." + attr_name
-        elif obj[0] == obj[0].upper(): # XXX HACK ALERT
+        elif obj[0] == obj[0].upper():  # XXX HACK ALERT
             call_name = UU + self.modpfx() + "__" + obj + ".prototype.__class__." + attr_name
         else:
             call_name = UU+self._name(v, current_klass) + "." + attr_name
 
         return call_name
 
-
     def _getattr2(self, v, current_klass, attr_name):
         if isinstance(v.expr, ast.Getattr):
             call_name = self._getattr2(v.expr, current_klass, v.attrname + "." + attr_name)
         elif isinstance(v.expr, ast.Name) and v.expr.name in self.module_imports():
-            call_name = UU+v.expr.name + '.__' +v.attrname+".prototype.__class__."+attr_name
+            call_name = UU+v.expr.name + '.__' + v.attrname+".prototype.__class__."+attr_name
         else:
             obj = self.expr(v.expr, current_klass)
             call_name = obj + "." + v.attrname + "." + attr_name
 
         return call_name
 
-
     def _class(self, node):
         """
         Handle a class definition.
@@ -761,12 +761,11 @@
                 if child.name == "__init__":
                     init_method = child
 
-
         if len(node.bases) == 0:
             base_class = "pyjslib.__Object"
         elif len(node.bases) == 1:
             if isinstance(node.bases[0], ast.Name):
-                if self.imported_classes.has_key(node.bases[0].name):
+                if node.bases[0].name in self.imported_classes:
                     base_class_ = self.imported_classes[node.bases[0].name] + '.__' + node.bases[0].name
                     base_class = self.imported_classes[node.bases[0].name] + '.' + node.bases[0].name
                 else:
@@ -777,8 +776,9 @@
                 # pass our class to self._name
                 base_class_ = self._name(node.bases[0].expr, None) + \
                              ".__" + node.bases[0].attrname
-                base_class = self._name(node.bases[0].expr, None) + \
-                             "." + node.bases[0].attrname
+                base_class = \
+                    self._name(node.bases[0].expr, None) + \
+                    "." + node.bases[0].attrname
             else:
                 raise TranslationError("unsupported type (in _class)", node.bases[0])
 
@@ -788,28 +788,28 @@
 
         print >>self.output, UU+class_name_ + " = function () {"
         # call superconstructor
-        #if base_class:
+        # if base_class:
         #    print >>self.output, "    __" + base_class + ".call(this);"
         print >>self.output, "}"
 
         if not init_method:
             init_method = ast.Function([], "__init__", ["self"], [], 0, None, [])
-            #self._method(init_method, current_klass, class_name)
+            # self._method(init_method, current_klass, class_name)
 
         # Generate a function which constructs the object
-        clsfunc = ast.Function([],
-           node.name,
-           init_method.argnames[1:],
-           init_method.defaults,
-           init_method.flags,
-           None,
-           [ast.Discard(ast.CallFunc(ast.Name("JS"), [ast.Const(
-#            I attempted lazy initialization, but then you can't access static class members
-#            "    if(!__"+base_class+".__was_initialized__)"+
-#            "        __" + class_name + "_initialize();\n" +
-            "    var instance = new " + UU + class_name_ + "();\n" +
-            "    if(instance.__init__) instance.__init__.apply(instance, arguments);\n" +
-            "    return instance;"
+        clsfunc = ast.Function(
+            [], node.name,
+            init_method.argnames[1:],
+            init_method.defaults,
+            init_method.flags,
+            None,
+            [ast.Discard(ast.CallFunc(ast.Name("JS"), [ast.Const(
+                #            I attempted lazy initialization, but then you can't access static class members
+                #            "    if(!__"+base_class+".__was_initialized__)"+
+                #            "        __" + class_name + "_initialize();\n" +
+                "    var instance = new " + UU + class_name_ + "();\n" +
+                "    if(instance.__init__) instance.__init__.apply(instance, arguments);\n" +
+                "    return instance;"
             )]))])
 
         self._function(clsfunc, False)
@@ -847,7 +847,6 @@
 
         print >> self.output, class_name_+".__initialize__();"
 
-
     def classattr(self, node, current_klass):
         self._assign(node, current_klass, True)
 
@@ -876,22 +875,25 @@
         if staticmethod:
             staticfunc = ast.Function([], class_name_+"."+node.name, node.argnames, node.defaults, node.flags, node.doc, node.code, node.lineno)
             self._function(staticfunc, True)
-            print >>self.output, "    " + UU+class_name_ + ".prototype.__class__." + node.name + " = " + class_name_+"."+node.name+";";
-            print >>self.output, "    " + UU+class_name_ + ".prototype.__class__." + node.name + ".static_method = true;";
+            print >>self.output, "    " + UU+class_name_ + ".prototype.__class__." + node.name + " = " + class_name_+"."+node.name+";"
+            print >>self.output, "    " + UU+class_name_ + ".prototype.__class__." + node.name + ".static_method = true;"
             return
         else:
             if len(arg_names) == 0:
                 raise TranslationError("methods must take an argument 'self' (in _method)", node)
             self.method_self = arg_names[0]
 
-            #if not classmethod and arg_names[0] != "self":
+            # if not classmethod and arg_names[0] != "self":
             #    raise TranslationError("first arg not 'self' (in _method)", node)
 
         normal_arg_names = arg_names[1:]
-        if node.kwargs: kwargname = normal_arg_names.pop()
-        if node.varargs: varargname = normal_arg_names.pop()
+        if node.kwargs:
+            kwargname = normal_arg_names.pop()
+        if node.varargs:
+            varargname = normal_arg_names.pop()
         declared_arg_names = list(normal_arg_names)
-        if node.kwargs: declared_arg_names.append(kwargname)
+        if node.kwargs:
+            declared_arg_names.append(kwargname)
 
         function_args = "(" + ", ".join(declared_arg_names) + ")"
 
@@ -904,13 +906,12 @@
         # default arguments
         self._default_args_handler(node, normal_arg_names, current_klass)
 
-        local_arg_names = normal_arg_names + declared_arg_names 
+        local_arg_names = normal_arg_names + declared_arg_names
 
         if node.varargs:
             self._varargs_handler(node, varargname, declared_arg_names, current_klass)
             local_arg_names.append(varargname)
 
-
         # stack of local variable names for this function call
         self.local_arg_stack.append(local_arg_names)
 
@@ -944,7 +945,7 @@
             print >>self.output, "    "+altexpr+".__name__ = '%s';" % node.name
 
         print >>self.output, UU + class_name_ + ".prototype.%s.__name__ = '%s';" % \
-                (node.name, node.name)
+            (node.name, node.name)
 
         if node.kwargs or len(node.defaults):
             print >>self.output, "    "+altexpr + ".parse_kwargs = " + fexpr + ".parse_kwargs;"
@@ -992,9 +993,9 @@
         elif isinstance(node, ast.Function):
             self._function(node, True)
         elif isinstance(node, ast.Printnl):
-           self._print(node, current_klass)
+            self._print(node, current_klass)
         elif isinstance(node, ast.Print):
-           self._print(node, current_klass)
+            self._print(node, current_klass)
         elif isinstance(node, ast.TryExcept):
             self._tryExcept(node, current_klass)
         elif isinstance(node, ast.Raise):
@@ -1009,30 +1010,28 @@
             haltException = self.module_prefix + "HaltException"
             isHaltFunction = self.module_prefix + "IsHaltException"
 
-            print >>self.output, '  } catch (__err) {'
-            print >>self.output, '      if (' + isHaltFunction + '(__err.name)) {'
-            print >>self.output, '          throw __err;'
-            print >>self.output, '      } else {'
-            print >>self.output, "          st = sys.printstack() + "\
-                                                + '"%s"' % lt + "+ '\\n' ;"
-            print >>self.output, '          alert("' + "Error in " \
-                                                + lt + '"' \
-                                                + '+"\\n"+__err.name+": "+__err.message'\
-                                                + '+"\\n\\nStack trace:\\n"' \
-                                                + '+st' \
-                                                + ');'
-            print >>self.output, '          debugger;'
-
-            print >>self.output, '          throw new ' + self.module_prefix + "HaltException();"
-            print >>self.output, '      }'
-            print >>self.output, '  }'
-
+            out = (
+                '  } catch (__err) {',
+                '      if (' + isHaltFunction + '(__err.name)) {',
+                '          throw __err;',
+                '      } else {',
+                '          st = sys.printstack() + ' + '"%s"' % lt + "+ '\\n' ;"
+                '          alert("' + 'Error in ' + lt + '"'
+                + '+"\\n"+__err.name+": "+__err.message'
+                + '+"\\n\\nStack trace:\\n"' + '+st' + ');',
+                '          debugger;',
+                '          throw new ' + self.module_prefix + 'HaltException();',
+                '      }',
+                '  }'
+            )
+            for s in out:
+                print >>self.output, s
 
     def get_line_trace(self, node):
         lineNum = "Unknown"
         srcLine = ""
         if hasattr(node, "lineno"):
-            if node.lineno != None:
+            if node.lineno is not None:
                 lineNum = node.lineno
                 srcLine = self.src[min(lineNum, len(self.src))-1]
                 srcLine = srcLine.replace('\\', '\\\\')
@@ -1040,9 +1039,9 @@
                 srcLine = srcLine.replace("'", "\\'")
 
         return self.raw_module_name + ".py, line " \
-               + str(lineNum) + ":"\
-               + "\\n" \
-               + "    " + srcLine
+            + str(lineNum) + ":"\
+            + "\\n" \
+            + "    " + srcLine
 
     def _augassign(self, node, current_klass):
         v = node.node
@@ -1056,15 +1055,14 @@
         rhs = self.expr(node.expr, current_klass)
         print >>self.output, "    " + lhs + " " + op + " " + rhs + ";"
 
-
-    def _assign(self, node, current_klass, top_level = False):
+    def _assign(self, node, current_klass, top_level=False):
         if len(node.nodes) != 1:
             tempvar = '__temp'+str(node.lineno)
             tnode = ast.Assign([ast.AssName(tempvar, "OP_ASSIGN", node.lineno)], node.expr, node.lineno)
             self._assign(tnode, current_klass, top_level)
             for v in node.nodes:
-               tnode2 = ast.Assign([v], ast.Name(tempvar, node.lineno), node.lineno)
-               self._assign(tnode2, current_klass, top_level)
+                tnode2 = ast.Assign([v], ast.Name(tempvar, node.lineno), node.lineno)
+                self._assign(tnode2, current_klass, top_level)
             return
 
         local_var_names = None
@@ -1093,7 +1091,7 @@
                     self.top_level_vars.add(v.name)
                     vname = self.modpfx() + v.name
                     if not self.modpfx() and v.name not in\
-                           self.method_imported_globals:
+                       self.method_imported_globals:
                         lhs = "var " + vname
                     else:
                         lhs = UU + vname
@@ -1140,7 +1138,7 @@
             tempName = "__tupleassign" + str(uniqueID) + "__"
             print >>self.output, "    var " + tempName + " = " + \
                                  self.expr(node.expr, current_klass) + ";"
-            for index,child in enumerate(v.getChildNodes()):
+            for index, child in enumerate(v.getChildNodes()):
                 rhs = tempName + ".__getitem__(" + str(index) + ")"
 
                 if isinstance(child, ast.AssAttr):
@@ -1156,7 +1154,7 @@
                         idx = self.expr(child.subs[0], current_klass)
                         value = self.expr(node.expr, current_klass)
                         print >>self.output, "    " + obj + ".__setitem__(" \
-                                           + idx + ", " + rhs + ");"
+                            + idx + ", " + rhs + ");"
                         continue
                 print >>self.output, "    " + lhs + " = " + rhs + ";"
             return
@@ -1168,14 +1166,13 @@
             print "b", repr(node.expr), rhs
         print >>self.output, "    " + lhs + " " + op + " " + rhs + ";"
 
-
     def _discard(self, node, current_klass):
-        
+
         if isinstance(node.expr, ast.CallFunc):
             debugStmt = self.debug and not self._isNativeFunc(node)
             if debugStmt and isinstance(node.expr.node, ast.Name) and \
                node.expr.node.name == 'import_wait':
-               debugStmt = False
+                debugStmt = False
             if debugStmt:
                 st = self.get_line_trace(node)
                 print >>self.output, "sys.addstack('%s');\n" % st
@@ -1194,12 +1191,11 @@
                 print >>self.output, "sys.popstack();\n"
 
         elif isinstance(node.expr, ast.Const):
-            if node.expr.value is not None: # Empty statements generate ignore None
+            if node.expr.value is not None:  # Empty statements generate ignore None
                 print >>self.output, self._const(node.expr)
         else:
             raise TranslationError("unsupported type (in _discard)", node.expr)
 
-
     def _if(self, node, current_klass):
         for i in range(len(node.tests)):
             test, consequence = node.tests[i]
@@ -1217,7 +1213,6 @@
 
             self._if_test(keyword, test, consequence, current_klass)
 
-
     def _if_test(self, keyword, test, consequence, current_klass):
         if test:
             expr = self.expr(test, current_klass)
@@ -1234,7 +1229,6 @@
 
         print >>self.output, "    }"
 
-
     def _from(self, node):
         for name in node.names:
             # look up "hack" in AppTranslator as to how findFile gets here
@@ -1248,7 +1242,6 @@
             else:
                 self.imported_classes[name[0]] = node.modname
 
-
     def _compare(self, node, current_klass):
         lhs = self.expr(node.expr, current_klass)
 
@@ -1272,7 +1265,6 @@
 
         return "(" + lhs + " " + op + " " + rhs + ")"
 
-
     def _not(self, node, current_klass):
         expr = self.expr(node.expr, current_klass)
 
@@ -1341,7 +1333,6 @@
         }
         """ % locals()
 
-
     def _while(self, node, current_klass):
         test = self.expr(node.test, current_klass)
         print >>self.output, "    while (pyjslib.bool(" + test + ")) {"
@@ -1352,7 +1343,6 @@
             raise TranslationError("unsupported type (in _while)", node.body)
         print >>self.output, "    }"
 
-
     def _const(self, node):
         if isinstance(node.value, int):
             return str(node.value)
@@ -1362,7 +1352,7 @@
             v = node.value
             if isinstance(node.value, unicode):
                 v = v.encode('utf-8')
-            return  "String('%s')" % escapejs(v)
+            return "String('%s')" % escapejs(v)
         elif node.value is None:
             return "null"
         else:
@@ -1388,8 +1378,8 @@
 
     def _mod(self, node, current_klass):
         if isinstance(node.left, ast.Const) and isinstance(node.left.value, StringType):
-           self.imported_js.add("sprintf.js") # Include the sprintf functionality if it is used
-           return "sprintf("+self.expr(node.left, current_klass) + ", " + self.expr(node.right, current_klass)+")"
+            self.imported_js.add("sprintf.js")  # Include the sprintf functionality if it is used
+            return "sprintf("+self.expr(node.left, current_klass) + ", " + self.expr(node.right, current_klass)+")"
         return self.expr(node.left, current_klass) + " % " + self.expr(node.right, current_klass)
 
     def _invert(self, node, current_klass):
@@ -1404,7 +1394,7 @@
     def _bitshiftright(self, node, current_klass):
         return self.expr(node.left, current_klass) + " >>> " + self.expr(node.right, current_klass)
 
-    def _bitxor(self,node, current_klass):
+    def _bitxor(self, node, current_klass):
         return " ^ ".join([self.expr(child, current_klass) for child in node.nodes])
 
     def _bitor(self, node, current_klass):
@@ -1459,11 +1449,11 @@
         if node.flags == "OP_APPLY":
             lower = "null"
             upper = "null"
-            if node.lower != None:
+            if node.lower is not None:
                 lower = self.expr(node.lower, current_klass)
-            if node.upper != None:
+            if node.upper is not None:
                 upper = self.expr(node.upper, current_klass)
-            return  "pyjslib.slice(" + self.expr(node.expr, current_klass) + ", " + lower + ", " + upper + ")"
+            return "pyjslib.slice(" + self.expr(node.expr, current_klass) + ", " + lower + ", " + upper + ")"
         else:
             raise TranslationError("unsupported flag (in _slice)", node)
 
@@ -1499,7 +1489,7 @@
             return self._invert(node, current_klass)
         elif isinstance(node, ast.Bitand):
             return "("+self._bitand(node, current_klass)+")"
-        elif isinstance(node,ast.LeftShift):
+        elif isinstance(node, ast.LeftShift):
             return self._bitshiftleft(node, current_klass)
         elif isinstance(node, ast.RightShift):
             return self._bitshiftright(node, current_klass)
@@ -1531,9 +1521,6 @@
             raise TranslationError("unsupported type (in expr)", node)
 
 
-
-import cStringIO
-
 def translate(file_name, module_name, debug=False):
     f = file(file_name, "r")
     src = f.read()
@@ -1545,7 +1532,7 @@
 
 
 class PlatformParser:
-    def __init__(self, platform_dir = "", verbose=True):
+    def __init__(self, platform_dir="", verbose=True):
         self.platform_dir = platform_dir
         self.parse_cache = {}
         self.platform = ""
@@ -1557,7 +1544,7 @@
     def parseModule(self, module_name, file_name):
 
         importing = False
-        if not self.parse_cache.has_key(file_name):
+        if file_name not in self.parse_cache:
             importing = True
             mod = compiler.parseFile(file_name)
             self.parse_cache[file_name] = mod
@@ -1631,12 +1618,14 @@
         target.code = source.code
         target.argnames = source.argnames
         target.defaults = source.defaults
-        target.doc = source.doc # @@@ not sure we need to do this any more
+        target.doc = source.doc  # @@@ not sure we need to do this any more
+
 
 def dotreplace(fname):
     path, ext = os.path.splitext(fname)
     return path.replace(".", "/") + ext
 
+
 class AppTranslator:
 
     def __init__(self, library_dirs=[], parser=None, dynamic=False,
@@ -1693,7 +1682,7 @@
         mod, override = self.parser.parseModule(module_name, file_name)
         if override:
             override_name = "%s.%s" % (self.parser.platform.lower(),
-                                           module_name)
+                                       module_name)
             self.overrides[override_name] = override_name
         if is_app:
             mn = '__main__'
@@ -1709,13 +1698,12 @@
         for module in t.imported_modules:
             if module not in self.library_modules:
                 self.library_modules.append(module)
-                #imported_js.update(set(t.imported_js))
-                #imported_modules_str += self._translate(
+                # imported_js.update(set(t.imported_js))
+                # imported_modules_str += self._translate(
                 #    module, False, debug=debug, imported_js=imported_js)
 
         return imported_modules_str + module_str
 
-
     def translate(self, module_name, is_app=True, debug=False,
                   library_modules=[]):
         app_code = cStringIO.StringIO()
@@ -1742,24 +1730,26 @@
             print >> app_code, self._translate(
                 module_name, is_app, debug=debug, imported_js=imported_js)
         for js in imported_js:
-           path = self.findFile(js)
-           if os.path.isfile(path):
-              if self.verbose:
-                  print 'Including JS', js
-              print >> lib_code,  '\n//\n// BEGIN JS '+js+'\n//\n'
-              print >> lib_code, file(path).read()
-              print >> lib_code,  '\n//\n// END JS '+js+'\n//\n'
-           else:
-              print >>sys.stderr, 'Warning: Unable to find imported javascript:', js
+            path = self.findFile(js)
+            if os.path.isfile(path):
+                if self.verbose:
+                    print 'Including JS', js
+                print >> lib_code,  '\n//\n// BEGIN JS '+js+'\n//\n'
+                print >> lib_code, file(path).read()
+                print >> lib_code,  '\n//\n// END JS '+js+'\n//\n'
+            else:
+                print >>sys.stderr, 'Warning: Unable to find imported javascript:', js
         return lib_code.getvalue(), app_code.getvalue()
 
+
 usage = """
   usage: %s file_name [module_name]
 """
 
+
 def main():
     import sys
-    if len(sys.argv)<2:
+    if len(sys.argv) < 2:
         print >> sys.stderr, usage % sys.argv[0]
         sys.exit(1)
     file_name = os.path.abspath(sys.argv[1])
@@ -1772,6 +1762,6 @@
         module_name = None
     print translate(file_name, module_name),
 
+
 if __name__ == "__main__":
     main()
-