import directory error

Steve Holden steve at holdenweb.com
Mon Jan 31 10:23:51 EST 2005


Olivier Noblanc ATOUSOFT wrote:

> Hello,
> 
> 
> When i want to import a .py fire from another subdirectory i make
> 
> import inc/setupxml
> 
> 
> but that make me an error message.
> 
> A man tell me to put a dot but that doesn't work.
> 
> Can you help me ?
> 
> Thanks.
> 
> 
> 
If you want to import a single .py (a Python module) then the ONLY way 
to achieve that is to make sure it appears in a directory that is a 
member of the sys.path list. (This is a slight simplification, but it 
will do as long as you are only importing from the file store).

There are various ways to affect the contents of sys.path, the best 
known of which include

    1. Setting the PYTHONPATH environment variable
    2. Creating *.pth files
    3. Altering sys.path inside site-customize.py in
       your standard library

Python does allow you to implement PACKAGES, which are directories 
containing

    a) a file called __init__.py and (optionally)
    b) other modules (.py files) and packages (directories
       containing __init__.py files).

The Python interpreter looks for packages in all the same places it 
looks for modules, but it imports packages by running the __init__.py 
file (as usual, this happens on the *first* time the package is imported).

So, for example, under Cygwin or Linux/Unix, I can define a package 
(with no Python in it, but still obeying the rules) as follows:

sholden at dellboy ~
$ mkdir mp1

sholden at dellboy ~
$ touch mp1/__init__.py

sholden at dellboy ~
$ touch mp1/rhubarb.py

sholden at dellboy ~
$ mkdir mp1/p2

sholden at dellboy ~
$ touch mp1/p2/__init__.py

sholden at dellboy ~
$ python
Python 2.4 (#1, Dec  4 2004, 20:10:33)
[GCC 3.3.3 (cygwin special)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
  >>> import sys
  >>> "" in sys.path
True
  >>> import mp1
  >>> import mp1.rhubarb
  >>> import mp1.p2
  >>>

sholden at dellboy ~
$ find mp1
mp1
mp1/p2
mp1/p2/__init__.py
mp1/p2/__init__.pyc
mp1/rhubarb.py
mp1/rhubarb.pyc
mp1/__init__.py
mp1/__init__.pyc

In this case mp1.rhubarb is a module from the mp1 package, mp1.p2 is a 
sub-package of mp1. You can see what's been compiled by the interpreter 
on import and when by looking at the .pyc files.

Does this help any?

regards
  Steve
-- 
Steve Holden               http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC      +1 703 861 4237  +1 800 494 3119



More information about the Python-list mailing list