python - Import with and without main scope -




i have 2 files, app.py , database.py in same directory. have following code snippets:

app.py

import database db = "demo_database" print(database.show_database_information()) 

database.py

from app import db database_username = "root" database_password = "password" def show_database_information():     information = {}     information["filename"] = db     information["username"] = database_username     information["password"] = database_password     return information 

when try run app.py got following error:

traceback (most recent call last):   file "k:\pyprac\circular_call\app.py", line 1, in <module>     import database   file "k:\pyprac\circular_call\database.py", line 1, in <module>     app import db   file "k:\pyprac\circular_call\app.py", line 3, in <module>     print(database.show_database_information()) attributeerror: module 'database' has no attribute 'show_database_information' 

then updated app.py , included __main__ check below:

app.py

import database db = "demo_database" if __name__ == '__main__':     print(database.show_database_information()) 

now runs smoothly without error.

i have several questions,

  1. what name of error occurred in first scenario? need explanation.
  2. why runs after including __main__ scope?
  3. what better approach of doing operations this?

man!! creating circular moment. let me tell how.

import database  # app.py 

but database.py imported db app. creating circular moment.

on other hand,

if __name__ == '__main__':   

this making database.py name of module instead of __main__ that's why it's working. nothing magical :)

update: placed from app import db line inside function show_database_information() hotfix you.





wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -