How does circular import work exactly in Python -


i have following code (run cpython 3.4):

how expect import work

basically red arrows explain how expected import work: h defined before importing test2. when test2 imports test1 it's not empty module anymore (with h) , h thing test2 wants.

i think contradicts http://effbot.org/zone/import-confusion.htm

any hints?

what you're missing fact from x import y, not solely imports y. imports module x first. it's mentioned in page:

from x import a, b, c imports module x, , creates references in current namespace given objects. or in other words, can use , b , c in program.

so, statement:

from test import h 

does not stop importing when reaches definition of h.

let's change file:

test.py

h = 3 if __name__ != '__main__': #check if it's imported     print('i'm still called!') ... 

when run test.py, you'll i'm still called! before error.

the condition checks whether script imported or not. in edited code, if add condition, you'll print when acts main script, not imported script.

here help:

  1. test imports test2 (h defined)
  2. test2 imports test, meets condition.
  3. the condition false - test imported -, so, test2 not going test2.j - doesn't exist yet.

hope helps!


Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -