[Tutor] Problem with modules

Kalle Svensson kalle@lysator.liu.se
Mon, 5 Aug 2002 22:09:01 +0200


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[Richard Seguin]
> from gui import *
> 
> def TEST():
>    print "Option 1"
> 
> gui()
...
> When you call the function gui() you would expect that the function
> TEST() would be known to gui.py wouldn't you? This may be a newbie
> question but the answer for this should put everything into
> perspective.

No.  Each module lives in it's own namespace.  Modifications to one
does not affect the others.  Think of it as dictionaries:

__main__ = {}                       # Start with an empty namespace.
                                    # This isn't true for real
                                    # modules, but enough for now.
__main__.update(get_module('gui'))  # from ... import * adds all names
                                    # in one module to another.
__main__['TEST'] = <function>       # def binds a function to a name.
__main__['gui']()                   # Call the function bound to 'gui'.

where the get_module function returns a dictionary with the name-value
mappings for another module.

The dictionary for the 'gui' module is not modified here.  You could
do something like this:

  import gui
  def TEST():
      print "Option 1"
  gui.TEST = TEST
  gui.gui()

but that's not considered good style.  Generally, you shouldn't modify
other modules' namespaces in this way, it leads to code that is
difficult to understand.  A better way might be to put the TEST
function in another module and import it in gui.py, or to pass it as
an argument to the gui function.

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE9TttGdNeA1787sd0RAjx0AJ9YxAyRCitj+cvbcvdBNTIvEBY/PwCgpPm8
8g03S+HfNi5QlRYTsi0H36I=
=0jkj
-----END PGP SIGNATURE-----