0

I try create class, which will return values to pretty print. I found this post python __str__ for an object but I still can't understand how I can improve my class.

Here is my class:

class PrintList(): 
    def __init__(self,lista):
        self.lista=lista
    def __str__(self):
        if isinstance(x[0] in self.lista, dict):           #for dicts in list
            return ','.join(str(item),'->',str(item[x]) for x in item) for item in self.lista
        else:         # for variables in list
            return ','.join(str(x) for x in self.lista)

and bug in first return:

return ','.join(str(item),'->',str(item[x]) for x in item) for item in self.lista
                                                                 ^
SyntaxError: invalid syntax

I try get the following result: key_dict->value_dict, etc.

Community
  • 1
  • 1
MartinP
  • 527
  • 5
  • 17

1 Answers1

3

You definitely have an invalid syntax in your comprehension/generator expression.

You should have written the expression as follows

return ','.join("{}->{}".format(item, item[x]) for x in item for item in self.lista)

Offtopic

As @MartijnPieter, for str.join, its faster to use a list comprehension rather than a generator expression notably because it needs to generate the data before stitching them togeter (a two pass algorithm). Please refer list comprehension without [ ], Python

Community
  • 1
  • 1
Abhijit
  • 62,056
  • 18
  • 131
  • 204
  • 1
    I'd use a list comprehension and not a generator expression; it is faster *for `str.join()`*. See [list comprehension without \[ \], Python](http://stackoverflow.com/a/9061024) – Martijn Pieters Sep 26 '14 at 08:54
  • @MartijnPieters: I know. I am just using the same format as OPs without introducing new concepts or digressing from the topic. If you see, OP is already using a generator expression, and I did not think would make sense to convert it to a list. – Abhijit Sep 26 '14 at 08:57
  • *shrug*. I'd add an extra paragraph explaining that a list comp would be the better option here and link to Raymond's answer, that's all. :-) – Martijn Pieters Sep 26 '14 at 08:59
  • @MartijnPieters: Ok, I have added a paragraph in the answer. – Abhijit Sep 26 '14 at 09:04