Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The general rule of thumb is that imports should be at the top of the file, as that makes code easier to follow, and that makes it easier to figure out what a module will need without having to go through all the code.</p> <p>The Python style guide covers some basic guidelines for how imports should look: <a href="http://www.python.org/dev/peps/pep-0008/#imports" rel="nofollow">http://www.python.org/dev/peps/pep-0008/#imports</a></p> <p>In practice, though, there are times when it makes sense to import from within a particular function. This comes up with imports that would be circular:</p> <pre><code># Module 1 from module2 import B class A(object): def do_something(self): my_b = B() ... # Module 2 from module1 import A class B(object): def do_something(self): my_a = A() ... </code></pre> <p>That won't work as is, but you could get around the circularity by moving the import:</p> <pre><code># Module 1 from module2 import B class A(object): def do_something(self): my_b = B() ... # Module 2 class B(object): def do_something(self): from module1 import A my_a = A() ... </code></pre> <p>Ideally, you would design the classes such that this would never come up, and maybe even include them in the same module. In that toy example, having each import the other really doesn't make sense. However, in practice, there are some cases where it makes more sense to include an import for one method within the method itself, rather than throwing everything into the same module, or extracting the method in question out to some other object.</p> <p>But, unless you have good reason to deviate, I say go with the top-of-the-module convention.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload