Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python iteration over non-sequence

Tags:

python

I have this piece of code which creates a note and adds to the notebook. When I run this I get a Iteration over non-sequence error.

import datetime
class Note:
    def __init__(self, memo, tags):
        self.memo = memo
        self.tags = tags
        self.creation_date = datetime.date.today()

def __str__(self):
    return 'Memo={0}, Tag={1}'.format(self.memo, self.tags)


class NoteBook:
     def __init__(self):
        self.notes = []

     def add_note(self,memo,tags):
        self.notes.append(Note(memo,tags))

if __name__ == "__main__":
    firstnote = Note('This is my first memo','example')
    print(firstnote)
    Notes = NoteBook()
    Notes.add_note('Added thru notes','example-1')
    Notes.add_note('Added thru notes','example-2')
    for note in Notes:
        print(note.memo)

Error:

C:\Python27\Basics\OOP\formytesting>python notebook.py  
Memo=This is my first memo, Tag=example  
Traceback (most recent call last):  
  File "notebook.py", line 27, in   
    for note in Notes:  
TypeError: iteration over non-sequence
like image 865
user1050619 Avatar asked Aug 08 '12 19:08

user1050619


2 Answers

You are trying to iterate over the object itself, which is returning the error. You want to iterate over the list inside the object, in this case Notes.notes (which is somewhat confusing naming, you may want to distinguish the internal list by using another name for the instance of the notebook object).

for note in Notes.notes:
    print(note.memo)
like image 73
pk-nb Avatar answered Sep 28 '22 04:09

pk-nb


Notes is an instance of NoteBook. To iterate over such an object, it needs an __iter__ method:

class NoteBook:

    def __iter__(self):
        return iter(self.notes)

PS. It is a PEP8 recommendation/convention in Python to use lowercase variable names for instances of classes, and CamelCase for class names. Following this convention will help you instantly recognize your class instances from your classes.

If you wish to follow this convention (and endear yourself to others who like this convention), change Notes to notes.

like image 37
unutbu Avatar answered Sep 28 '22 05:09

unutbu