Importing modules

alex23 wuwei23 at gmail.com
Wed Jan 21 12:29:19 EST 2009


On Jan 22, 1:45 am, Mudcat <mnati... at gmail.com> wrote:
> This is something I've wondered about for a while. I know that
> theoretically Python is supposed to auto-recognize duplicate imports;
> however I've run into problems in the past if I didn't arrange the
> imports in a certain way across multiple files. As a result, I worry
> about conflicts that arise because something has been imported twice.
> So...I'm not sure if Python *always* gets this correct.

Python -will- only import something once. Every time you import a
module, Python looks up its module dictionary to see if it contains a
module of that name. If not, it imports it, adds a new module object
and binds the name to that object in the calling namespace. If it does
exist, it retrieves the module object from the dict, and then binds
the name to that object in the calling namespace.

Its best to view each Python module as a completely independent
namespace. If you need to use something from another module within
that namespace, you need to import it. If I have a function 'f' in
module 'm' that uses 'math.pow', I can't just import 'f' into a module
that has imported 'math', I need to import 'math' into 'm'. Regardless
of where the function (or class) ends up being used, where it is
defined -must- have all of the imports that function needs to run.

If you're having to set up your imports in a specific order, odds are
you have either a circular dependency or are overusing 'from <module>
import *'. You should -never- (IMO) do something like 'from <some
library> import x, y, z' in module 'a' and then 'from a import *' in
module 'b'. If 'b' uses x, y & z, it should import them itself. If you
-must- use 'import *', specify exactly what should be exported via
'__all__'...in most cases, it should be restricted to only objects
defined within that module.

> I think it would great to have access to a file (like the __init__.py
> file for packages) which all the files in the same directory would
> have access to for common imports. That way you could push out the
> repeated imports and also clean up the look a little bit as well.

Well, you can always stick those imports into a 'common.py' and do
'from common import *' in each file that uses them. But doing so can
be a pain to maintain and debug for anything more than the most simple
of applications. Being able to see a module's dependencies clearly
listed at the top of the file is exceptionally handy.



More information about the Python-list mailing list