does the order in which the modules are placed in a file matters ?

Dan Strohl D.Strohl at F5.com
Wed Dec 16 11:42:01 EST 2015


For the general modules it doesn't matter, however using if you are using any non-standard packages, and If there are duplicate names in any of the modules and if you import them with a "*" (as some packages suggest), it can cause you to end up referring to an object you were not intending to.

For example, if you have found a package called "foo", and the instructions on it are to import it as:

from foo import *

Then you have another package called "bar" with the same instructions... so now you have:

from foo import *
from bar import *

In both of these there is a class called "snafu", when you do this:

from foo import *
from bar import *

SITUATION = snafu()

You are going to get bar.snafu(), not foo.snafu()

This can of course be gotten around by doing:

import foo
import bar

SITUATION = foo.snafu()

(or a number of other approaches using "as" etc...)

Note, using * is dis-recommended, though pretty often done, for more information on using *, see: https://docs.python.org/2/tutorial/modules.html#importing-from-a-package 

Dan Strohl


-----Original Message-----
From: Python-list [mailto:python-list-bounces+d.strohl=f5.com at python.org] On Behalf Of Chris Angelico
Sent: Wednesday, December 16, 2015 8:14 AM
Cc: python-list at python.org
Subject: Re: does the order in which the modules are placed in a file matters ?

On Thu, Dec 17, 2015 at 3:09 AM, Ganesh Pal <ganesh1pal at gmail.com> wrote:
> Iam on python 2.7 and linux .I need to know if we need to place the 
> modules  in a particular or it doesn't matter at all
>
> order while writing the program
>
> For Example
>
> import os
> import shlex
> import subprocess
> import time
> import sys
> import logging
> import  plaftform.cluster
> from util import run

The order of the import statements is the order the modules will get loaded up. As a general rule this won't matter; when it comes to standard library modules, you can generally assume that you can put them in any order without it making any difference. It's common to order them in some aesthetically-pleasing way (maybe alphabetical order, or maybe sort them by the length of the name - whatever you like).

There is a broad convention that standard library modules get imported first, and modules that are part of the current project get imported afterwards. But even that doesn't usually matter very much.

ChrisA
--
https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list