views:

41

answers:

1

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?

+1  A: 

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.

ChristopheD
yes i just thought that including at the main file it would work, and it didnt i tried that and it work, now theres no way it going to work like in php or ruby that just including all at the main file, in this couples of month i've being digging in python and i like it a lot bue coming from php is i bit different... i didnt find a tutorial that really explain me how to make something solid...
i-Malignus