I've discovered a new pattern. I wonder if anyone else has this pattern or has any opinion about it.
Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of
import foo
from bar.baz import quux
def myFunction():
foo.this.that(quux)
I move all my imports into the function where they're actually used., like this:
def myFunction():
import foo
from bar.baz import quux
foo.this.that(quux)
This does a few things. First, I rarely accidentally pollute my modules with the contents of other modules. I could set the __all__
variable for the module, but then i'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.
Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it. Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.