Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python, accessing a psycopg2 form a def?

i'm trying to make a group of defs in one file so then i just can import them whenever i want to make a script in python

i have tried this:

def get_dblink( dbstring):
"""
Return a database cnx.
"""
global psycopg2 
try
    cnx = psycopg2.connect( dbstring)
except Exception, e:
    print "Unable to connect to DB. Error [%s]" % ( e,)
    exit( )

but i get this error: global name 'psycopg2' is not defined

in my main file script.py

i have:

import psycopg2, psycopg2.extras
from misc_defs import * 

hostname = '192.168.10.36'
database = 'test'
username = 'test'
password = 'test'

dbstring = "host='%s' dbname='%s' user='%s' password='%s'" % ( hostname, database, username, password)

cnx = get_dblink( dbstring)

can anyone give me a hand?

like image 395
Ignus Avatar asked May 21 '26 05:05

Ignus


1 Answers

You just need to import psycopg2 in your first snippet.

If you need to there's no problem to 'also' import it in the second snippet (Python makes sure the modules are only imported once). Trying to use globals for this is bad practice.

So: at the top of every module, import every module which is used within that particular module.

Also: note that from x import * (with wildcards) is generally frowned upon: it clutters your namespace and makes your code less explicit.

like image 101
ChristopheD Avatar answered May 22 '26 17:05

ChristopheD