I’ve had my share of headaches with Python modules (see last post and less recent ones). So I decided to review the use(s) and rules concerning modules.
Turns out that the best place to look things up is still Mark Lutz’s “Learning Python”, see chapters 18 – 21. I was glad to read the following, which I had wondered about just the other day:
Code at the top level of a module file (not nested in a function) runs as soon as Python reaches it during an import; because of that, it can’t reference names assigned lower in the file.
Because when importing modules, code is compiled right then, line by line.