Commits

James Mills  committed c0a4527

- Implemented forwards compatibility (trying to keep backwards compatibility
for Python 2.x) for Python 3.x

  • Participants
  • Parent commits 55877f3

Comments (0)

Files changed (3)

+synax: glob
+
+.egg-info
+__pycache__
 Distributed under MIT license [http://opensource.org/licenses/mit-license.html].
 """
 
-__revision__ = "$LastChangedRevision$"
 __author__ = 'Ero Carrera'
-__version__ = '1.0.%d' % int( __revision__[21:-2] )
+__version__ = '1.0.15'
 __license__ = 'MIT'
 
 import os
 import copy
 try:
     import dot_parser
-except Exception, e:
-    print "Couldn't import dot_parser, loading of dot files will not be possible."
+except Exception:
+    print("Couldn't import dot_parser, loading of dot files will not be possible.")
     
 
 
     'penwidth', 'peripheries', 'sortv', 'style', 'target', 'tooltip'] )
             
 
+try:
+    long
+except NameError:
+    long = int
+
 #
 # Extented version of ASPN's Python Cookbook Recipe:
 # Frozen dictionaries.
 #
 class frozendict(dict):
     def _blocked_attribute(obj):
-        raise AttributeError, "A frozendict cannot be modified."
+        raise AttributeError("A frozendict cannot be modified.")
     _blocked_attribute = property(_blocked_attribute)
 
     __delitem__ = __setitem__ = clear = _blocked_attribute
         for arg in args:
             if isinstance(arg, dict):
                 arg = copy.copy(arg)
-                for k, v in arg.iteritems():
+                for k, v in arg.items():
                     if isinstance(v, dict):
                         arg[k] = frozendict(v)
                     elif isinstance(v, list):
         try:
             return self._cached_hash
         except AttributeError:
-            h = self._cached_hash = hash(tuple(sorted(self.iteritems())))
+            h = self._cached_hash = hash(tuple(sorted(self.items())))
             return h
 
     def __repr__(self):
             return 'True'
         return 'False'
 
-    if not isinstance( s, basestring ):
+    if not isinstance( s, str ):
         return s
 
     if needs_quotes(s):
     representing the graph.
     """
     
-    fd = file(path, 'rb')
+    fd = open(path, 'rb')
     data = fd.read()
     fd.close()
     
     return graph
 
 
-def graph_from_adjacency_matrix(matrix, node_prefix= u'', directed=False):
+def graph_from_adjacency_matrix(matrix, node_prefix="", directed=False):
     """Creates a basic graph out of an adjacency matrix.
     
     The matrix has to be a list of rows of values
     
     if os.path.isdir(path) : 
     
-        for prg in progs.iterkeys():
+        for prg in progs.keys():
     
             if progs[prg]:
                 continue
                         path = os.path.join(path, "bin")
                         progs = __find_executables(path)
                         if progs is not None :
-                            #print "Used Windows registry"
+                            #print*"Used Windows registry")
                             return progs
                 
-                except Exception, excp:
+                except Exception:
                     #raise excp
                     pass
                 else:
 
     # Method 2 (Linux, Windows etc)
     #
-    if os.environ.has_key('PATH'):
+    if "PATH" in os.environ:
     
         for path in os.environ['PATH'].split(os.pathsep):
             progs = __find_executables(path)
             if progs is not None :
-                #print "Used path"
+                #print*"Used path")
                 return progs
 
     # Method 3 (Windows only)
         # machine (might be on drive D:, or in a different language)
         #
         
-        if os.environ.has_key('PROGRAMFILES'):
+        if "PROGRAMFILES" in os.environ:
         
             # Note, we could also use the win32api to get this
             # information, but win32api may not be installed.
         
         if progs is not None :
         
-            #print "Used default install location"
+            #print("Used default install location")
             return progs
 
 
         
         progs = __find_executables(path)
         if progs is not None :
-            #print "Used path"
+            #print*"Used path")
             return progs
 
     # Failed to find GraphViz
     return None
     
 
-class Common:
+class Common(object):
     """Common information to several classes.
     
     Should not be directly used, several classes are derived from
 
 
 
-class Node(object, Common):
+class Node(Common):
     """A graph node.
     
     This class represents a graph's node with all its attributes.
     """
 
     def __init__(self, name = '', obj_dict = None, **attrs):
+        super(Node, self).__init__()
     
         #
         # Nodes will take attributes of all other types because the defaults
             # Remove the compass point
             #
             port = None
-            if isinstance(name, basestring) and not name.startswith('"'):
+            if isinstance(name, str) and not name.startswith('"'):
                 idx = name.find(':')
                 if idx > 0:
                     name, port = name[:idx], name[idx:]
 
         node_attr = list()
 
-        for attr, value in self.obj_dict['attributes'].iteritems():
+        for attr, value in self.obj_dict['attributes'].items():
             if value is not None:
                 node_attr.append( '%s=%s' % (attr, quote_if_necessary(value) ) )
             else:
 
 
 
-class Edge(object,  Common ):
+class Edge(Common):
     """A graph edge.
     
     This class represents a graph's edge with all its attributes.
 
 
     def __init__(self, src='', dst='', obj_dict=None, **attrs):
+        super(Edge, self).__init__()
     
         if isinstance(src, (list, tuple)) and dst == '':
             src, dst = src
         """
         
         if not isinstance(edge, Edge):
-            raise Error, "Can't compare and edge to a non-edge object."
+            raise Error("Can't compare and edge to a non-edge object.")
             
         if self.get_parent_graph().get_top_graph_type() == 'graph':
         
 
         edge_attr = list()
         
-        for attr, value in self.obj_dict['attributes'].iteritems():
+        for attr, value in self.obj_dict['attributes'].items():
         
             if value is not None:
                 edge_attr.append( '%s=%s' % (attr, quote_if_necessary(value) ) )
     
     
     
-class Graph(object, Common):
+class Graph(Common):
     """Class representing a graph in Graphviz's dot language.
 
     This class implements the methods to work on a representation
     """
     
 
-    def __init__(self, graph_name='G', obj_dict=None, graph_type='digraph', strict=False,
-        suppress_disconnected=False, simplify=False, **attrs):
+    def __init__(self, graph_name='G', obj_dict=None,
+            graph_type='digraph', strict=False,
+            suppress_disconnected=False, simplify=False, **attrs):
+
+        super(Graph, self).__init__()
 
         if obj_dict is not None:
             self.obj_dict = obj_dict
             self.obj_dict['attributes'] = dict(attrs)
             
             if graph_type not in ['graph', 'digraph']:
-                raise Error, 'Invalid type "%s". Accepted graph types are: graph, digraph, subgraph' % graph_type
+                raise Error('Invalid type "%s". Accepted graph types are: graph, digraph, subgraph' % graph_type)
     
     
             self.obj_dict['name'] = graph_name
         if isinstance(name, Node):
             name = name.get_name()
         
-        if self.obj_dict['nodes'].has_key(name):
+        if name in self.obj_dict['nodes']:
         
             if index is not None and index < len(self.obj_dict['nodes'][name]):
                 del self.obj_dict['nodes'][name][index]
         
         match = list()
         
-        if self.obj_dict['nodes'].has_key(name):
+        if name in self.obj_dict['nodes']:
         
             match.extend( [ Node( obj_dict = obj_dict ) for obj_dict in self.obj_dict['nodes'][name] ])
         
         
         node_objs = list()
         
-        for node, obj_dict_list in self.obj_dict['nodes'].iteritems():
+        for node, obj_dict_list in self.obj_dict['nodes'].items():
                 node_objs.extend( [ Node( obj_dict = obj_d ) for obj_d in obj_dict_list ] )
         
         return node_objs
             
         edge_points = ( graph_edge.get_source(), graph_edge.get_destination() )
 
-        if self.obj_dict['edges'].has_key(edge_points):
+        if edge_points in self.obj_dict['edges']:
         
             edge_list = self.obj_dict['edges'][edge_points]
             edge_list.append(graph_edge.obj_dict)
         if isinstance(dst, Node):
             dst = dst.get_name()
         
-        if self.obj_dict['edges'].has_key( (src, dst) ):
+        if (src, dst) in self.obj_dict['edges']:
         
             if index is not None and index < len(self.obj_dict['edges'][(src, dst)]):
                 del self.obj_dict['edges'][(src, dst)][index]
 
         match = list()
         
-        if self.obj_dict['edges'].has_key( edge_points ) or (
-            self.get_top_graph_type() == 'graph' and self.obj_dict['edges'].has_key( edge_points_reverse )):
+        if edge_points in self.obj_dict['edges'] or (
+            self.get_top_graph_type() == 'graph' and edge_points_reverse in self.obj_dict['edges']):
         
             edges_obj_dict = self.obj_dict['edges'].get(
                 edge_points,
         
         edge_objs = list()
         
-        for edge, obj_dict_list in self.obj_dict['edges'].iteritems():
+        for edge, obj_dict_list in self.obj_dict['edges'].items():
                 edge_objs.extend( [ Edge( obj_dict = obj_d ) for obj_d in obj_dict_list ] )
         
         return edge_objs
         if not isinstance(sgraph, Subgraph) and not isinstance(sgraph, Cluster):
             raise TypeError('add_subgraph() received a non subgraph class object')
             
-        if self.obj_dict['subgraphs'].has_key(sgraph.get_name()):
+        if sgraph.get_name() in self.obj_dict['subgraphs']:
         
             sgraph_list = self.obj_dict['subgraphs'][ sgraph.get_name() ]
             sgraph_list.append( sgraph.obj_dict )
         
         match = list()
         
-        if self.obj_dict['subgraphs'].has_key( name ):
+        if name in self.obj_dict['subgraphs']:
         
             sgraphs_obj_dict = self.obj_dict['subgraphs'].get( name )
         
         
         sgraph_objs = list()
         
-        for sgraph, obj_dict_list in self.obj_dict['subgraphs'].iteritems():
+        for sgraph, obj_dict_list in self.obj_dict['subgraphs'].items():
                 sgraph_objs.extend( [ Subgraph( obj_dict = obj_d ) for obj_d in obj_dict_list ] )
         
         return sgraph_objs
     
         self.obj_dict['parent_graph'] = parent_graph
         
-        for obj_list in self.obj_dict['nodes'].itervalues():
+        for obj_list in self.obj_dict['nodes'].values():
             for obj in obj_list:
                 obj['parent_graph'] = parent_graph
 
-        for obj_list in self.obj_dict['edges'].itervalues():
+        for obj_list in self.obj_dict['edges'].values():
             for obj in obj_list:
                 obj['parent_graph'] = parent_graph
 
-        for obj_list in self.obj_dict['subgraphs'].itervalues():
+        for obj_list in self.obj_dict['subgraphs'].values():
             for obj in obj_list:
                 Graph(obj_dict=obj).set_parent_graph(parent_graph)
 
             graph.append( '%s %s {\n' % (self.obj_dict['type'], self.obj_dict['name']) )
 
 
-        for attr in self.obj_dict['attributes'].iterkeys():
+        for attr in self.obj_dict['attributes'].keys():
         
             if self.obj_dict['attributes'].get(attr, None) is not None:
        
         edges_done = set()
         
         edge_obj_dicts = list()
-        for e in self.obj_dict['edges'].itervalues():
+        for e in self.obj_dict['edges'].values():
             edge_obj_dicts.extend(e)
             
         if edge_obj_dicts:
             edge_src_set, edge_dst_set = set(), set()
             
         node_obj_dicts = list()
-        for e in self.obj_dict['nodes'].itervalues():
+        for e in self.obj_dict['nodes'].values():
             node_obj_dicts.extend(e)
 
         sgraph_obj_dicts = list()
-        for sg in self.obj_dict['subgraphs'].itervalues():
+        for sg in self.obj_dict['subgraphs'].values():
             sgraph_obj_dicts.extend(sg)
 
         
     
      
     def __init__(self, *argsl, **argsd):
-        Graph.__init__(self, *argsl, **argsd)
+        super(Dot, self).__init__(*argsl, **argsd)
 
         self.shape_files = list()
 
         graph is going to be rendered.
         """
         
-        if isinstance( file_paths, basestring ):
+        if isinstance( file_paths, str ):
             self.shape_files.append( file_paths )
             
         if isinstance( file_paths, (list, tuple) ):
         if prog is None:
             prog = self.prog
         
-        dot_fd = file(path, "w+b")
+        dot_fd = open(path, "w+b")
         if format == 'raw':
-            dot_fd.write(self.to_string())
+            dot_fd.write(self.to_string().encode("utf-8"))
         else:
             dot_fd.write(self.create(prog, format))
         dot_fd.close()
                 raise InvocationException(
                     'GraphViz\'s executables not found' )
                 
-        if not self.progs.has_key(prog):
+        if not prog in self.progs:
             raise InvocationException(
                 'GraphViz\'s executable "%s" not found' % prog )
             
         
             # Get its data
             #
-            f = file(img, 'rb')
+            f = open(img, 'rb')
             f_data = f.read()
             f.close()
             
             # And copy it under a file with the same name in the temporary directory
             #
-            f = file( os.path.join( tmp_dir, os.path.basename(img) ), 'wb' )
+            f = open( os.path.join( tmp_dir, os.path.basename(img) ), 'wb' )
             f.write(f_data)
             f.close()
 
             stdout_output.append(data)
         stdout.close()
             
-        stdout_output = ''.join(stdout_output)
+        stdout_output = b''.join(stdout_output)
         
         if not stderr.closed:
             stderr_output = list()
                 'Program terminated with status: %d. stderr follows: %s' % (
                     status, stderr_output) )
         elif stderr_output:
-            print stderr_output
+            print(stderr_output)
         
         # For each of the image files...
         #
 #!/usr/bin/env python
 
 try:
+    from setuptools import setup
+except ImportError:
     from distutils.core import setup
-except ImportError, excp:
-    from setuptools import setup
     
 import pydot
 import os