Reputation: 1044
I'm confused about import order and use. As you can see in the code below, in main I first import psycopg2. THEN I import data_connect (that has dependency on psycopg2), so two questions: (1) Why doesn't the interpreter see that I already imported psycopg2? (2) How do I fix this? Thanks!
Error message:
File "C:\home\partscobra.com\wwwroot\data_connect.py" in data_connect:
db_conn = psycopg2.connect(...
NameError: name 'psycopg2' is not defined"
main.py:
import psycopg2
from data_connect import data_connect, data_cursor
#error here
[snip]
data_connect.py:
def data_connect():
t_host = "blahblahblah"
t_port = "5432"
t_dbname = "inventory"
t_user = "remote"
t_pw = "blahblahblah"
db_conn = psycopg2.connect(
host=t_host,
port=t_port,
dbname=t_dbname,
user=t_user,
password=t_pw
)
db_conn.autocommit=True
return db_conn
def data_cursor():
db_conn = data_connect()
db_cursor = db_conn.cursor()
return db_cursor
Upvotes: 1
Views: 759
Reputation: 59112
Stuff you import gets added to the current namespace (in this case the global namespace of the main
module), not to every module (e.g. data_connect
).
If you import psycopg2
in data_connect.py
then psycopg2
will be added to the global namespace of your data_connect
module.
Upvotes: 3