I've discovered a new pattern. Is this pattern well known or what is the 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.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…