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,
- what name of error occurred in first scenario? need explanation.
- why runs after including
__main__scope? - 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
Post a Comment