Python Etiquette: Importing Modules

Posted by F3AR3DLEGEND on Stack Overflow See other posts from Stack Overflow or by F3AR3DLEGEND
Published on 2013-06-29T22:12:50Z Indexed on 2013/06/29 22:21 UTC
Read the original article Hit count: 205

Filed under:
|

Say I have two Python modules:

module1.py:

import module2
def myFunct(): print "called from module1"

module2.py:

def myFunct(): print "called from module2"
def someFunct(): print "also called from module2"

If I import module1, is it better etiquette to re-import module2, or just refer to it as module1.module2?

For example (someotherfile.py):

import module1
module1.myFunct() # prints "called from module1"
module1.module2.myFunct() # prints "called from module2"

I can also do this: module2 = module1.module2. Now, I can directly call module2.myFunct().

However, I can change module1.py to:

from module2 import *
def myFunct(): print "called from module1"

Now, in someotherfile.py, I can do this:

import module1
module1.myFunct() # prints "called from module1"; overrides module2
module1.someFunct() # prints "also called from module2"

Also, by importing *, help('module1') shows all of the functions from module2.

On the other hand, (assuming module1.py uses import module2), I can do: someotherfile.py:

 import module1, module2
 module1.myFunct() # prints "called from module1"
 module2.myFunct() # prints "called from module2"

Again, which is better etiquette and practice? To import module2 again, or to just refer to module1's importation?

© Stack Overflow or respective owner

Related posts about python

Related posts about coding-style