0

I have a class definition here:

class Graph:
    def __init__(self,directional = False,simple=True,Filename=None):
        self.adjacencyList = {}
        self.directional = directional
        self.simple = simple

and I designed __str__ method for it like this:

def __str__(self):
    simple = "Simple: "+ str(self.simple)+"\n"
    directional = "Directional: " + str(self.directional)+"\n"
    items = "{\n"
    for vertex in self.adjacencyList.keys():
        items = items +"\t"+str(vertex)+str(self.adjacencyList[vertex])+"\n"
    items += "}"
    string = simple + directional + items
    return string

I found it is so verbose and I am thinking maybe there is some cleaner way to do it using fewer lines of code.

Can you give me some suggestions?

Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
Bob Fang
  • 6,963
  • 10
  • 39
  • 72

3 Answers3

4

Use string formatting instead:

    def __str__(self)
        items = '\n'.join(['\t{0}{1}'.format(k, v)
            for k, v in self.adjencyList.iteritems()])
        return (
            "Simple: {0.simple}\n"
            "Directional: {0.directional}\n"
            "{{\t{1}\n}}"
        ).format(self, items)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    Square brackets are not necessary here. Maybe they were needed some versions ago. – zch Jan 11 '13 at 18:40
  • @zch: See http://stackoverflow.com/a/9061024; `''.join()` needs two passes over the items, and using a generator expression slows that down. Using a list comprehension instead if *faster*. So, no, brackets are technically not needed, but are recommended anyway. – Martijn Pieters Jan 11 '13 at 18:54
2

The pprint.pformat function should help you. It will return a string that is nicely formatted for printing.

>>> import pprint
>>> adjacencyList = { 1: 100, 2: 200, 3: 300, 4: 400, 5: 500, 6: 600, 7: 700, 8: 800, 9: 900, 10: 1000 }
>>> s = pprint.pformat(adjacencyList)
>>> print s
{1: 100,
 2: 200,
 3: 300,
 4: 400,
 5: 500,
 6: 600,
 7: 700,
 8: 800,
 9: 900,
 10: 1000}

While not exactly the same as the output in your original code, I think this is quite readable and close.

I would then rewrite your whole __str__ function as:

def __str__(self):
    return (
        "Simple: {0.simple}\n"
        "Directional: {0.directional}\n"
        "{1}"
    ).format(self, pprint.pformat(self.adjacencyList))
ford
  • 10,687
  • 3
  • 47
  • 54
1

Try this:

items = ''.join(['\t%s%s\n' % (k,v) for k,v in self.adjacencyList.items()])
return 'Simple: %s\nDirectional: %s\n{\n%s}' % (self.simple, self.directional, items)
Luke
  • 11,374
  • 2
  • 48
  • 61