Browse Source

Fix various python code quality issues

See also https://lgtm.com/projects/g/open62541/open62541/alerts
Stefan Profanter 5 years ago
parent
commit
81148ab1eb

+ 0 - 2
tools/c2rst.py

@@ -5,8 +5,6 @@
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 import sys
-import os
-import binascii
 import re
 
 # Converts a header file to restructured text documentation

+ 0 - 1
tools/certs/create_self-signed.py

@@ -5,7 +5,6 @@
 
 import sys
 import os
-import shutil
 import socket
 
 if len(sys.argv) < 2:

+ 16 - 9
tools/generate_datatypes.py

@@ -15,7 +15,7 @@ import xml.etree.ElementTree as etree
 import itertools
 import argparse
 import csv
-from nodeset_compiler.opaque_type_mapping import opaque_type_mapping, get_base_type_for_opaque
+from nodeset_compiler.opaque_type_mapping import get_base_type_for_opaque
 
 types = OrderedDict() # contains types that were already parsed
 typedescriptions = {} # contains type nodeids
@@ -93,9 +93,14 @@ def getNodeidTypeAndId(nodeId):
 
 class Type(object):
     def __init__(self, outname, xml, namespace):
-        self.name = xml.get("Name")
+        self.name = None
+        if xml is not None:
+            self.name = xml.get("Name")
+            self.typeIndex = makeCIdentifier(outname.upper() + "_" + self.name.upper())
+        else:
+            self.typeIndex = makeCIdentifier(outname.upper())
+
         self.ns0 = ("true" if namespace == 0 else "false")
-        self.typeIndex = makeCIdentifier(outname.upper() + "_" + self.name.upper())
         self.outname = outname
         self.description = ""
         self.pointerfree = "false"
@@ -105,18 +110,19 @@ class Type(object):
         else:
             self.builtin = "false"
         self.members = [StructMember("", self, False)] # Returns one member: itself. Overwritten by some types.
-        for child in xml:
-            if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
-                self.description = child.text
-                break
+        if xml is not None:
+            for child in xml:
+                if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
+                    self.description = child.text
+                    break
 
     def datatype_c(self):
-        xmlEncodingId = "0"
+        # xmlEncodingId = "0"
         binaryEncodingId = "0"
         if self.name in typedescriptions:
             description = typedescriptions[self.name]
             typeid = "{%s, %s}" % (description.namespaceid, getNodeidTypeAndId(description.nodeid))
-            xmlEncodingId = description.xmlEncodingId
+            # xmlEncodingId = description.xmlEncodingId
             binaryEncodingId = description.binaryEncodingId
         else:
             typeid = "{0, UA_NODEIDTYPE_NUMERIC, {0}}"
@@ -202,6 +208,7 @@ class Type(object):
 
 class BuiltinType(Type):
     def __init__(self, name):
+        Type.__init__(self, name, None, 0)
         self.name = name
         self.ns0 = "true"
         self.typeIndex = makeCIdentifier("UA_TYPES_" + self.name.upper())

+ 0 - 3
tools/generate_nodeid_header.py

@@ -6,9 +6,6 @@
 
 from __future__ import print_function
 import sys
-import platform
-import getpass
-import time
 import argparse
 from io import open
 

+ 0 - 3
tools/generate_statuscode_descriptions.py

@@ -6,9 +6,6 @@
 
 from __future__ import print_function
 import sys
-import platform
-import getpass
-import time
 import argparse
 from io import open
 

+ 10 - 10
tools/nodeset_compiler/backend_graphviz.py

@@ -35,14 +35,14 @@ def printDotGraphWalk(nodeset, depth=1, filename="out.dot", rootNode=None,
     """
     iter = depth
     processed = []
-    if rootNode == None or not isinstance(rootNode, Node) or not rootNode in nodeset.nodes:
+    if rootNode is None or not isinstance(rootNode, Node) or not rootNode in nodeset.nodes:
         root = nodeset.getRoot()
     else:
         root = rootNode
 
     file = codecs.open(filename, 'w+', encoding='utf-8')
 
-    if root == None:
+    if root is None:
         return
 
     file.write("digraph ns {\n")
@@ -63,13 +63,13 @@ def printDotGraphWalk(nodeset, depth=1, filename="out.dot", rootNode=None,
                     if not tgt in processed:
                         file.write(nodePrintDot(tgt))
                         processed.append(tgt)
-                        if ref.isForward == False and followInverse == True:
-                            for ref in tgt.inverseReferences:
-                                refs.append(ref)
+                        if ref.isForward is False and followInverse is True:
+                            for inverseRef in tgt.inverseReferences:
+                                refs.append(inverseRef)
                             tmp = tmp + tgt.references  # + tgt.getInverseReferences()
-                        elif ref.isForward == True:
-                            for ref in tgt.references:
-                                refs.append(ref)
+                        elif ref.isForward:
+                            for targetRef in tgt.references:
+                                refs.append(targetRef)
         refs = tmp
         iter = iter - 1
 
@@ -137,12 +137,12 @@ def addNodeToGraph(nodeset, node, graph, alreadyAdded=set(), relevantReferences=
 
 
 def generateGraphvizCode(nodeset, filename="dependencies", rootNode=None, excludeNodeIds=[]):
-    if rootNode == None or not isinstance(rootNode, Node) or not rootNode in nodeset.nodes:
+    if rootNode is None or not isinstance(rootNode, Node) or not rootNode in nodeset.nodes:
         root = nodeset.getRoot()
     else:
         root = rootNode
 
-    if root == None:
+    if root is None:
         return
 
     g = gv.dot.Digraph(name="NodeSet Dependency", format='pdf', )

+ 7 - 1
tools/nodeset_compiler/backend_open62541.py

@@ -19,7 +19,6 @@
 ###
 
 from __future__ import print_function
-import string
 from os.path import basename
 import logging
 import codecs
@@ -29,8 +28,15 @@ try:
 except ImportError:
     from io import StringIO
 
+import sys
+if sys.version_info[0] >= 3:
+    # strings are already parsed to unicode
+    def unicode(s):
+        return s
+
 logger = logging.getLogger(__name__)
 
+from datatypes import NodeId
 from nodes import *
 from nodeset import *
 from backend_open62541_nodes import generateNodeCode_begin, generateNodeCode_finish, generateReferenceCode

+ 1 - 4
tools/nodeset_compiler/backend_open62541_nodes.py

@@ -19,7 +19,6 @@
 from nodes import *
 from backend_open62541_datatypes import *
 import re
-import datetime
 import logging
 
 logger = logging.getLogger(__name__)
@@ -29,8 +28,6 @@ logger = logging.getLogger(__name__)
 #################
 
 def generateNodeIdPrintable(node):
-    CodePrintable = "NODE_"
-
     if isinstance(node.id, NodeId):
         CodePrintable = node.__class__.__name__ + "_" + str(node.id)
     else:
@@ -248,7 +245,7 @@ def generateExtensionObjectSubtypeCode(node, parent, nodeset, global_var_code, r
     encFieldIdx = 0
     code.append("{")
     for subv in node.value:
-        encField = node.encodingRule[encFieldIdx]
+        # encField = node.encodingRule[encFieldIdx]
         encFieldIdx = encFieldIdx + 1
         if subv.valueRank is None or subv.valueRank == 0:
             code.append(

+ 49 - 43
tools/nodeset_compiler/datatypes.py

@@ -20,6 +20,14 @@ import sys
 import logging
 from datetime import datetime
 
+
+__all__ = ['valueIsInternalType', 'Value', 'Boolean', 'Number', 'Integer',
+           'UInteger', 'Byte', 'SByte',
+           'Int16', 'UInt16', 'Int32', 'UInt32', 'Int64', 'UInt64', 'Float', 'Double',
+           'String', 'XmlElement', 'ByteString', 'ExtensionObject', 'LocalizedText',
+           'NodeId', 'ExpandedNodeId', 'DateTime', 'QualifiedName', 'StatusCode',
+           'DiagnosticInfo', 'Guid']
+
 logger = logging.getLogger(__name__)
 import xml.dom.minidom as dom
 
@@ -34,10 +42,10 @@ if sys.version_info[0] >= 3:
 
 
 def getNextElementNode(xmlvalue):
-    if xmlvalue == None:
+    if xmlvalue is None:
         return None
     xmlvalue = xmlvalue.nextSibling
-    while not xmlvalue == None and not xmlvalue.nodeType == xmlvalue.ELEMENT_NODE:
+    while not xmlvalue is None and not xmlvalue.nodeType == xmlvalue.ELEMENT_NODE:
         xmlvalue = xmlvalue.nextSibling
     return xmlvalue
 
@@ -49,15 +57,13 @@ def valueIsInternalType(valueTypeString):
                    'qualifiedname', 'expandednodeid', 'xmlelement', 'integer', 'uinteger']
 
 class Value(object):
-    def __init__(self, xmlelement=None):
+    def __init__(self):
         self.value = None
         self.alias = None
         self.dataType = None
         self.encodingRule = []
         self.isInternal = False
         self.valueRank = None
-        if xmlelement:
-            self.parseXML(xmlelement)
 
     def getValueFieldByAlias(self, fieldname):
         if not isinstance(self.value, list):
@@ -128,13 +134,10 @@ class Value(object):
         return t
 
     def checkXML(self, xmlvalue):
-        if xmlvalue == None or xmlvalue.nodeType != xmlvalue.ELEMENT_NODE:
+        if xmlvalue is None or xmlvalue.nodeType != xmlvalue.ELEMENT_NODE:
             logger.error("Expected XML Element, but got junk...")
             return
 
-    def parseXML(self, xmlvalue):
-        raise Exception("Cannot parse arbitrary value of no type.")
-
     def parseXMLEncoding(self, xmlvalue, parentDataTypeNode, parent):
         self.checkXML(xmlvalue)
         if not "value" in xmlvalue.localName.lower():
@@ -173,7 +176,7 @@ class Value(object):
 
         # Encoding may be partially handed down (iterative call). Only resort to
         # type definition if we are not given a specific encoding to match
-        if encodingPart == None:
+        if encodingPart is None:
             enc = parentDataTypeNode.getEncoding()
         else:
             enc = encodingPart
@@ -186,7 +189,7 @@ class Value(object):
             # 1: [ [ 'Alias', [...], n] ] or single alias for possible multipart
             if isinstance(enc[0], six.string_types):
                 # 0: 'BuiltinType'
-                if alias != None:
+                if alias is not None:
                     if not xmlvalue.localName == alias and not xmlvalue.localName == enc[0]:
                         logger.error(str(parent.id) + ": Expected XML element with tag " + alias + " but found " + xmlvalue.localName + " instead")
                         return None
@@ -211,10 +214,10 @@ class Value(object):
                                                   alias=alias, encodingPart=enc[0], valueRank=enc[2] if len(enc)>2 else None)
         elif len(enc) == 3 and isinstance(enc[0], six.string_types):
             # [ 'Alias', [...], 0 ]          aliased multipart
-            if alias == None:
+            if alias is None:
                 alias = enc[0]
             # if we have an alias and the next field is multipart, keep the alias
-            elif alias != None and len(enc[1]) > 1:
+            elif alias is not None and len(enc[1]) > 1:
                 alias = enc[0]
             # otherwise drop the alias
             return self.__parseXMLSingleValue(xmlvalue, parentDataTypeNode, parent,
@@ -256,7 +259,7 @@ class Value(object):
             ebodypart = ebody.firstChild
             if not ebodypart.nodeType == ebodypart.ELEMENT_NODE:
                 ebodypart = getNextElementNode(ebodypart)
-            if ebodypart == None:
+            if ebodypart is None:
                 logger.error(str(parent.id) + ": Expected ExtensionObject to hold a variable of type " + str(parentDataTypeNode.browseName) + " but found nothing.")
                 return None
 
@@ -269,13 +272,13 @@ class Value(object):
             ebodypart = ebodypart.firstChild
             if not ebodypart.nodeType == ebodypart.ELEMENT_NODE:
                 ebodypart = getNextElementNode(ebodypart)
-            if ebodypart == None:
+            if ebodypart is None:
                 logger.error(str(parent.id) + ": Description of dataType " + str(parentDataTypeNode.browseName) + " in ExtensionObject is empty/invalid.")
                 return None
 
             extobj.value = []
             for e in enc:
-                if not ebodypart == None:
+                if not ebodypart is None:
                     extobj.value.append(extobj.__parseXMLSingleValue(ebodypart, parentDataTypeNode, parent, alias=None, encodingPart=e))
                 else:
                     logger.error(str(parent.id) + ": Expected encoding " + str(e) + " but found none in body.")
@@ -302,7 +305,7 @@ class Boolean(Value):
         # Expect <Boolean>value</Boolean> or
         #        <Aliasname>value</Aliasname>
         self.checkXML(xmlvalue)
-        if xmlvalue.firstChild == None:
+        if xmlvalue.firstChild is None:
             self.value = "false"  # Catch XML <Boolean /> by setting the value to a default
         else:
             if "false" in unicode(xmlvalue.firstChild.data).lower():
@@ -320,89 +323,89 @@ class Number(Value):
         # Expect <Int16>value</Int16> or any other valid number type, or
         #        <Aliasname>value</Aliasname>
         self.checkXML(xmlvalue)
-        if xmlvalue.firstChild == None:
+        if xmlvalue.firstChild is None:
             self.value = 0  # Catch XML <Int16 /> by setting the value to a default
         else:
             self.value = int(unicode(xmlvalue.firstChild.data))
 
 class Integer(Number):
     def __init__(self, xmlelement=None):
-        Value.__init__(self)
+        Number.__init__(self)
         if xmlelement:
             self.parseXML(xmlelement)
 
 class UInteger(Number):
     def __init__(self, xmlelement=None):
-        Value.__init__(self)
+        Number.__init__(self)
         if xmlelement:
             self.parseXML(xmlelement)
 
 class Byte(UInteger):
     def __init__(self, xmlelement=None):
-        Value.__init__(self)
+        UInteger.__init__(self)
         if xmlelement:
             self.parseXML(xmlelement)
 
 class SByte(Integer):
     def __init__(self, xmlelement=None):
-        Value.__init__(self)
+        Integer.__init__(self)
         if xmlelement:
             self.parseXML(xmlelement)
 
 class Int16(Integer):
     def __init__(self, xmlelement=None):
-        Value.__init__(self)
+        Integer.__init__(self)
         if xmlelement:
             self.parseXML(xmlelement)
 
 class UInt16(UInteger):
     def __init__(self, xmlelement=None):
-        Value.__init__(self)
+        UInteger.__init__(self)
         if xmlelement:
             self.parseXML(xmlelement)
 
 class Int32(Integer):
     def __init__(self, xmlelement=None):
-        Value.__init__(self)
+        Integer.__init__(self)
         if xmlelement:
             self.parseXML(xmlelement)
 
 class UInt32(UInteger):
     def __init__(self, xmlelement=None):
-        Value.__init__(self)
+        UInteger.__init__(self)
         if xmlelement:
             self.parseXML(xmlelement)
 
 class Int64(Integer):
     def __init__(self, xmlelement=None):
-        Value.__init__(self)
+        Integer.__init__(self)
         if xmlelement:
             self.parseXML(xmlelement)
 
 class UInt64(UInteger):
     def __init__(self, xmlelement=None):
-        Value.__init__(self)
+        UInteger.__init__(self)
         if xmlelement:
             self.parseXML(xmlelement)
 
 class Float(Number):
     def __init__(self, xmlelement=None):
-        Value.__init__(self)
+        Number.__init__(self)
         if xmlelement:
-            self.parseXML(xmlelement)
+            Float.parseXML(self, xmlelement)
 
     def parseXML(self, xmlvalue):
         # Expect <Float>value</Float> or
         #        <Aliasname>value</Aliasname>
         self.checkXML(xmlvalue)
-        if xmlvalue.firstChild == None:
+        if xmlvalue.firstChild is None:
             self.value = 0.0  # Catch XML <Float /> by setting the value to a default
         else:
             self.value = float(unicode(xmlvalue.firstChild.data))
 
 class Double(Float):
     def __init__(self, xmlelement=None):
-        Value.__init__(self)
+        Float.__init__(self)
         if xmlelement:
             self.parseXML(xmlelement)
 
@@ -424,18 +427,18 @@ class String(Value):
             self.value = xmlvalue
             return
         self.checkXML(xmlvalue)
-        if xmlvalue.firstChild == None:
+        if xmlvalue.firstChild is None:
             self.value = ""  # Catch XML <String /> by setting the value to a default
         else:
             self.value = unicode(xmlvalue.firstChild.data)
 
 class XmlElement(String):
     def __init__(self, xmlelement=None):
-        Value.__init__(self, xmlelement)
+        String.__init__(self, xmlelement)
 
 class ByteString(Value):
     def __init__(self, xmlelement=None):
-        Value.__init__(self, xmlelement)
+        Value.__init__(self)
 
     def parseXML(self, xmlvalue):
         # Expect <ByteString>value</ByteString>
@@ -443,7 +446,7 @@ class ByteString(Value):
             self.value = xmlvalue
             return
         self.checkXML(xmlvalue)
-        if xmlvalue.firstChild == None:
+        if xmlvalue.firstChild is None:
             self.value = []  # Catch XML <ByteString /> by setting the value to a default
         else:
             self.value = b64decode(xmlvalue.firstChild.data).decode("utf-8")
@@ -542,7 +545,7 @@ class NodeId(Value):
         self.checkXML(xmlvalue)
 
         # Catch XML <NodeId />
-        if xmlvalue.firstChild == None:
+        if xmlvalue.firstChild is None:
             logger.error("No value is given, which is illegal for Node Types...")
             self.value = None
         else:
@@ -572,6 +575,9 @@ class NodeId(Value):
     def __eq__(self, nodeId2):
         return (str(self) == str(nodeId2))
 
+    def __ne__(self, other):
+        return not self.__eq__(other)
+
     def __repr__(self):
         return str(self)
 
@@ -599,7 +605,7 @@ class DateTime(Value):
         #        2013-08-13T21:00:05.0000L
         #        </DateTime> or </AliasName>
         self.checkXML(xmlvalue)
-        if xmlvalue.firstChild == None:
+        if xmlvalue.firstChild is None:
             # Catch XML <DateTime /> by setting the value to a default
             self.value = datetime(2001, 1, 1)
         else:
@@ -613,10 +619,10 @@ class DateTime(Value):
                 timestr = timestr[:-1]
             try:
                 self.value = datetime.strptime(timestr, "%Y-%m-%dT%H:%M:%S")
-            except:
+            except Exception:
                 try:
                     self.value = datetime.strptime(timestr, "%Y-%m-%d")
-                except:
+                except Exception:
                     logger.error("Timestring format is illegible. Expected 2001-01-30T21:22:23 or 2001-01-30, but got " + \
                                  timestr + " instead. Time will be defaultet to now()")
                     self.value = datetime(2001, 1, 1)
@@ -655,7 +661,7 @@ class QualifiedName(Value):
 
 class StatusCode(UInt32):
     def __init__(self, xmlelement=None):
-        Value.__init__(self, xmlelement)
+        UInt32.__init__(self, xmlelement)
 
 class DiagnosticInfo(Value):
     def __init__(self, xmlelement=None):
@@ -675,7 +681,7 @@ class Guid(Value):
 
     def parseXML(self, xmlvalue):
         self.checkXML(xmlvalue)
-        if xmlvalue.firstChild == None:
+        if xmlvalue.firstChild is None:
             self.value = [0, 0, 0, 0]  # Catch XML <Guid /> by setting the value to a default
         else:
             self.value = unicode(xmlvalue.firstChild.data)
@@ -686,7 +692,7 @@ class Guid(Value):
             for g in self.value:
                 try:
                     tmp.append(int("0x" + g, 16))
-                except:
+                except Exception:
                     logger.error("Invalid formatting of Guid. Expected {01234567-89AB-CDEF-ABCD-0123456789AB}, got " + \
                                  unicode(xmlvalue.firstChild.data))
                     tmp = [0, 0, 0, 0, 0]

+ 19 - 12
tools/nodeset_compiler/nodes.py

@@ -20,6 +20,10 @@ import sys
 import logging
 from datatypes import *
 
+__all__ = ['Reference', 'RefOrAlias', 'Node', 'ReferenceTypeNode',
+           'ObjectNode', 'VariableNode', 'VariableTypeNode',
+           'MethodNode', 'ObjectTypeNode', 'DataTypeNode', 'ViewNode']
+
 logger = logging.getLogger(__name__)
 
 if sys.version_info[0] >= 3:
@@ -50,6 +54,9 @@ class Reference(object):
     def __eq__(self, other):
         return str(self) == str(other)
 
+    def __ne__(self, other):
+        return not self.__eq__(other)
+
     def __hash__(self):
         return hash(str(self))
 
@@ -191,7 +198,7 @@ class ReferenceTypeNode(Node):
         self.symmetric = False
         self.inverseName = ""
         if xmlelement:
-            self.parseXML(xmlelement)
+            ReferenceTypeNode.parseXML(self, xmlelement)
 
     def parseXML(self, xmlelement):
         Node.parseXML(self, xmlelement)
@@ -213,7 +220,7 @@ class ObjectNode(Node):
         Node.__init__(self)
         self.eventNotifier = 0
         if xmlelement:
-            self.parseXML(xmlelement)
+            ObjectNode.parseXML(self, xmlelement)
 
     def parseXML(self, xmlelement):
         Node.parseXML(self, xmlelement)
@@ -235,7 +242,7 @@ class VariableNode(Node):
         self.value = None
         self.xmlValueDef = None
         if xmlelement:
-            self.parseXML(xmlelement)
+            VariableNode.parseXML(self, xmlelement)
 
     def parseXML(self, xmlelement):
         Node.parseXML(self, xmlelement)
@@ -282,7 +289,7 @@ class VariableNode(Node):
             return False
 
         # FIXME: Don't build at all or allocate "defaults"? I'm for not building at all.
-        if self.xmlValueDef == None:
+        if self.xmlValueDef is None:
             #logger.warn("Variable " + self.browseName() + "/" + str(self.id()) + " is not initialized. No memory will be allocated.")
             return False
 
@@ -301,7 +308,7 @@ class VariableTypeNode(VariableNode):
         VariableNode.__init__(self)
         self.isAbstract = False
         if xmlelement:
-            self.parseXML(xmlelement)
+            VariableTypeNode.parseXML(self, xmlelement)
 
     def parseXML(self, xmlelement):
         Node.parseXML(self, xmlelement)
@@ -316,7 +323,7 @@ class MethodNode(Node):
         self.userExecutable = True
         self.methodDecalaration = None
         if xmlelement:
-            self.parseXML(xmlelement)
+            MethodNode.parseXML(self, xmlelement)
 
     def parseXML(self, xmlelement):
         Node.parseXML(self, xmlelement)
@@ -333,7 +340,7 @@ class ObjectTypeNode(Node):
         Node.__init__(self)
         self.isAbstract = False
         if xmlelement:
-            self.parseXML(xmlelement)
+            ObjectTypeNode.parseXML(self, xmlelement)
 
     def parseXML(self, xmlelement):
         Node.parseXML(self, xmlelement)
@@ -383,7 +390,7 @@ class DataTypeNode(Node):
         self.__definition__ = []
         self.__isEnum__     = False
         if xmlelement:
-            self.parseXML(xmlelement)
+            DataTypeNode.parseXML(self, xmlelement)
 
     def parseXML(self, xmlelement):
         Node.parseXML(self, xmlelement)
@@ -484,7 +491,7 @@ class DataTypeNode(Node):
             logger.debug("")
             return self.__baseTypeEncoding__
 
-        if self.__xmlDefinition__ == None:
+        if self.__xmlDefinition__ is None:
             # Check if there is a supertype available
             for ref in self.references:
                 if ref.isForward:
@@ -606,10 +613,10 @@ class DataTypeNode(Node):
 class ViewNode(Node):
     def __init__(self, xmlelement=None):
         Node.__init__(self)
-        self.containsNoLoops == False
-        self.eventNotifier == False
+        self.containsNoLoops = False
+        self.eventNotifier = False
         if xmlelement:
-            self.parseXML(xmlelement)
+            ViewNode.parseXML(self, xmlelement)
 
     def parseXML(self, xmlelement):
         Node.parseXML(self, xmlelement)

+ 11 - 8
tools/nodeset_compiler/nodeset.py

@@ -19,17 +19,23 @@
 from __future__ import print_function
 import sys
 import xml.dom.minidom as dom
-from struct import pack as structpack
-from time import struct_time, strftime, strptime, mktime
 import logging
 import codecs
 import re
+import six
+
+__all__ = ['NodeSet', 'getSubTypesOf']
 
 logger = logging.getLogger(__name__)
 
+from datatypes import *
 from nodes import *
 from opaque_type_mapping import opaque_type_mapping
-import codecs
+
+if sys.version_info[0] >= 3:
+    # strings are already parsed to unicode
+    def unicode(s):
+        return s
 
 ####################
 # Helper Functions #
@@ -65,12 +71,10 @@ def extractNamespaces(xmlfile):
     infile = codecs.open(xmlfile.name, encoding='utf-8')
     foundURIs = False
     nsline = ""
-    line = infile.readline()
     for line in infile:
         if "<namespaceuris>" in line.lower():
             foundURIs = True
         elif "</namespaceuris>" in line.lower():
-            foundURIs = False
             nsline = nsline + line
             break
         if foundURIs:
@@ -179,7 +183,7 @@ class NodeSet(object):
         if ndtype == 'referencetype':
             node = ReferenceTypeNode(xmlelement)
 
-        if node == None:
+        if node is None:
             return None
 
         node.modelUri = modelUri
@@ -227,7 +231,7 @@ class NodeSet(object):
         try:
             modelTag = nodeset.getElementsByTagName("Models")[0].getElementsByTagName("Model")[0]
             modelUri = modelTag.attributes["ModelUri"].nodeValue
-        except:
+        except Exception:
             # Ignore exception and try to use namespace array
             modelUri = None
 
@@ -278,7 +282,6 @@ class NodeSet(object):
         of the target node is "DefaultBinary"
         """
         node = self.nodes[nodeId]
-        refId = NodeId()
         for ref in node.references:
             if ref.referenceType.ns == 0 and ref.referenceType.i == 38:
                 refNode = self.nodes[ref.target]

+ 2 - 1
tools/nodeset_compiler/nodeset_compiler.py

@@ -24,6 +24,7 @@
 
 import logging
 import argparse
+from datatypes import NodeId
 from nodeset import *
 
 parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter)
@@ -149,7 +150,7 @@ for blacklist in args.blacklistFiles:
     for line in blacklist.readlines():
         line = line.replace(" ", "")
         id = line.replace("\n", "")
-        if ns.getNodeByIDString(id) == None:
+        if ns.getNodeByIDString(id) is None:
             logger.info("Can't blacklist node, namespace does currently not contain a node with id " + str(id))
         else:
             ns.removeNodeById(line)

+ 0 - 5
tools/update_copyright_header.py

@@ -13,11 +13,6 @@ import sys
 from git import *
 from shutil import move
 
-try:
-    from StringIO import StringIO
-except ImportError:
-    from io import StringIO
-
 if sys.version_info[0] >= 3:
     # strings are already parsed to unicode
     def unicode(s):