0

I need help figuring out why I am getting the following error:

Traceback (most recent call last):
  File "prawtest3.py", line 25, in <module>
    commentMatcher()
  File "prawtest3.py", line 13, in commentMatcher
    commentCollection.append(comment)
UnboundLocalError: local variable 'commentCollection' referenced before assignment

This is my code. For background information, I am trying to create a reddit bot that compares a persons comments and then pms a user when the person they are monitoring submits a new comment. If you see a problem with the functionality as well, feel free to share your input. I just need to diagnose my code first to get rid of the syntactical errors before worrying about the semantic ones.

import praw
import time 

r = praw.Reddit('PRAW related-question monitor by u/testpurposes v 1.0.')
r.login()
user = r.get_redditor('krumpqueen')
commentCollection = []
commentComparison = []

def commentMatcher():
    comments = user.get_comments(limit = 4)
    for comment in comments:
        commentCollection.append(comment)
    time.sleep(60)
    comments = user.get_comments(limit = 4)
    for comment in comments:
        commentComparision.append(comment)
    if commentCollection[1] != commentComparision[1]:
        r.send_message('krumpqueen', 'just made a new comment', 'go check now')
        commentCollection = list(commentComparision)
    else:
    r.send_message('krumpqueen', 'did not made a new comment', 'sorry')

while(True):
    commentMatcher()
Anon1234567890
  • 51
  • 2
  • 2
  • 7

2 Answers2

1

Your use of commentCollection makes python (incorrectly1) assume that commentCollection is a local (since you have an assignment to it later and no global statement). When you try to append to the local (which hasn't been created yet) python throws the UnboundLocalError.

1Of course, it's not python making an incorrect assumption, That's how the language is designed to work.

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • That's not what happens; if it were, the error would be raised at the point of the assignment to `commentCollection`, not the attempt to `append` to it. – user2357112 Feb 04 '14 at 03:20
  • @user2357112 -- Thanks, you're quite right. I've updated (hopefully correcting my error). – mgilson Feb 04 '14 at 03:28
1

You do commentCollection = list(commentComparision) inside of commentMatcher. Because you've done this, Python concludes you have a local name commentCollection.

Your code fails for the same reason that the code

def foo():
    bar.append(3)
    bar = []

would fail.

To get commentCollection = list(commentComparision) to a) rebind the global name commentCollection, and b) not make it look like this is a local name at all, add global commentCollection as the first line in the definition of commentMatcher.

In serious code, you wouldn't want to manage your state as globals like this, but rather you'd make an object.

Mike Graham
  • 73,987
  • 14
  • 101
  • 130