Referencing Data structures from a different file?

John Hunter jdhunter at nitace.bsd.uchicago.edu
Wed Nov 13 14:39:13 EST 2002


>>>>> "e-tones" == e-tones co uk <admin at e-tones.co.uk> writes:

    e-tones> Hi all, I have 2 files...  main.py data_structs.py

    e-tones> In data_structs I have a list and a dicionary, how do I
    e-tones> make it so main.py can access these data structures?

In the directory in which data_structs.py resides, create an empty
file called __init__.py.  This will allow other code to import
data_structs as a module.  In a unix like operating system, you can

  cd /path/to/data_structs
  touch __init__.py

You then need to add /path/to/data_structs to your PYTHONPATH.  In a
UNIX like environment, you would do

 setenv PYTHONPATH /path/to/data_structs   # csh and friends
 export PYTHONPATH=/path/to/data_structs   # bash and friends


Now, with your updated PYTHONPATH set, you can in main.py:

import data_structs

print data_structs.mylist
print data_structs.mydict

This may not be the best design.  There is a nice python pattern
called the Borg (which is like a Singleton in other languages) that
allows you to share objects across modules.

  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531

For a tutorial on creating and using your own modules in python,
consult http://www.python.org/doc/current/tut/node8.html.

Have fun!
John Hunter




More information about the Python-list mailing list