5

I have an error (shown in title) which occurs when I run this script:

import psycopg2

conn                =  None
conn_string         = "host='localhost' dbname='localdb' user='someuser' password='abracadabra'"


def connectDb():
    if conn is not None:   # Error occurs on this line
        return

    # print the connection string we will use to connect
    print "Connecting to database\n ->%s" % (conn_string)

conn has global scope, and is assigned to None before being referenced in the function - why the error message?

Homunculus Reticulli
  • 65,167
  • 81
  • 216
  • 341
  • You haven't pasted in the whole function body. The problem arises because you are rebinding the variable later on in this scope – John La Rooy Dec 21 '11 at 09:42

1 Answers1

13

In python you have to declare your global variables which you want to alter in functions with the global keyword:

def connectDb():
    global conn
    if conn is not None:   # Error occurs on this line
        return
    ...

My guess is that you are going to assign some value to conn somewhere later in the function, so you have to use the global keyword.

Constantinius
  • 34,183
  • 8
  • 77
  • 85