where is best place for import statements?

Graham Ashton gashton at cmedltd.com
Sun Oct 26 06:19:48 EST 2003


On Thu, 23 Oct 2003 14:52:07 +0000, Matthew Wilson wrote:
> I'm writing a bunch of classes, several of which need functions and
> variables defined in the math module.  In some instances, I'm going to
> import my module like this:
> 
> import myshapes
> 
> and then in others, I'll do:
> 
> from myshapes import Circle

You're best off avoiding importing things with from, except under
certain specific circumstances. If you use it to import classes or
variables from other modules then you run the risk of circular
imports, which are horrid.

It's generally considered better style to do this instead:

    import myshapes
    
    circle = myshapes.Circle()

as (apart from avoiding the technical problems of "from") you then
benefit from the contextual clues that the myshapes prefix gives
you. It's a boon for others reading your code, or for yourself a few
months down the line.

> from myshapes import *

Don't even go there, it's usually a bad habit. It makes for difficult
to follow code, and can also reduce performance under some
circumstances.

> How do I make sure that no matter how I import stuff from myshapes.py, I
> always also import the math module?  Should I write all of my functions
> like so:

If myshapes imports math, then users of myshapes that don't need to
refer to math themselves will never need to import it themselves. The
convention is to group your import statements at the top of your
module.

See the Imports section of PEP 8 for more:

  http://www.python.org/peps/pep-0008.html

Hope that helps.




More information about the Python-list mailing list