Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnboundLocalError: local variable 'conn' referenced before assignment [duplicate]

Tags:

python

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?

like image 455
Homunculus Reticulli Avatar asked Sep 01 '26 08:09

Homunculus Reticulli


1 Answers

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.

like image 105
Constantinius Avatar answered Sep 03 '26 23:09

Constantinius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!