简体   繁体   中英

Python 3.8 order of import modules and custom modules

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

Stuff you import gets added to the current namespace (in this case the global namespace of the main module), not to every module (eg data_connect ).

If you import psycopg2 in data_connect.py then psycopg2 will be added to the global namespace of your data_connect module.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM