[Tutor] Importing global variables and classes from other modules

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sun Dec 21 23:29:38 EST 2003



On Sun, 21 Dec 2003, Venkatesh Babu wrote:

> I have a main module which has few functions and in one of the
> functions, I have given an import statement so that I can get the
> functions and global variables present in other module into my main
> module's name space.

Hi Venkatesh,

Other folks have already pointed out why the above isn't working.  But
just as a reality check: are you sure you want to do this?


It's usually a very bad idea to do a 'from foo import *' --- it ties
together your module extremely closely to the imported module, and it
becomes a lot more difficult to see where a certain variable came from.

Simple example: if I see the code,

###
def f():
    print 'hello'

from some_module import *

f()
###

then I have no idea if the last function call, 'f()', refers to the f
that's just been defined at the top.  Why would I feel worried?  Because
any name in 'some_module' may have clobbered things in my own namespace,
and if 'some_module' itself defines an 'f', that'll override my 'f'.


The official Python Tutorial mentions 'from foo import *' is a statement
to avoid writing in real code:

http://python.org/doc/current/tut/node8.html#SECTION008410000000000000000


If you must make a module with global variables, it might be best to just
do the simple import:

###
import global_module
###

and refer to values in that module by explicitely refering to
global_module:

###
print global_module.some_variable_name
###



> But my problem is that the functions and other global variables present
> sub are not getting imported to my main module. Can any body suggest me
> what is the right method to do, the condition being that the import
> should happen only if I call f1.

Wait, wait.  Doing a conditional import might be a very bad idea from a
debugging standpoint.

Can you show us why you want to import this way?  That context might help
us to suggest better alternatives, if there are any.


Good luck to you!




More information about the Tutor mailing list