[Tutor] Cross-Module Interaction
Steven D'Aprano
steve at pearwood.info
Sat Feb 26 06:11:40 CET 2011
Corey Richardson wrote:
> My first thought was to have a module specifically for holding things
> like that, global objects that all the interacting modules need access
> to. I did a simple test with a lib module, and then a few modules that
> simply added things to a list called g in that lib module, but the
> changes did not persist (tested with another module that printed the
> contents of lib.g)
Perhaps you should give a *simple* example, but what you describe should
work. Let's start with a very simple library module:
# lib.py
g = []
Now let's import it and use it from another module:
# a.py
import lib
def do_stuff():
lib.g.append(42)
Save those two files as named, and then import them into the interactive
interpreter:
[steve at sylar ~]$ python
Python 2.5 (r25:51908, Nov 6 2007, 16:54:01)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import lib
>>> import a
>>> lib.g
[]
>>> a.do_stuff()
>>> lib.g
[42]
Of course, when your application exists (or in this case, the
interactive session), the changes to lib.g will be lost because they
only exist in memory. If you want data to persist across application
runs, you need to arrange for the application to save the data to disk,
and then read it again when it starts up.
Python has many tools for working with persistent data: Windows-style
ini files (module config parser), XML, JSON, Mac-style plists, YAML
(third-party module only), and pickles, to name only a few.
--
Steven
More information about the Tutor
mailing list