A smarter(?) package importer.

Prabhu Ramachandran prabhu at aero.iitm.ernet.in
Wed Nov 7 06:28:49 CET 2001


I am not sure if its 'correct' to attach a 4KB Python script on this
list.  Yes, its pretty small but I guess the number of people on the
list is large enough that its not the right thing to do?

Anyway, I managed to get knee.py to do what I wanted i.e.:

  (1) Check if module is available in the same directory, if available
  - use it.

  (2) If not found walk up to parent dir.  Check there, if not there
  go up until out of package.

  (3) If not found in (2) look at sys.path for module.

I've tested it a bit and it seems to work well.  It does not add
something like __.foo to refer to a parent package.  Also, using this
version of knee.py enables one to renest packages without any hassle.
I've put up two tiny files for download at a friends machine:


The relevant files are 

    my_import.py - which is simply an enhanced knee.py (with one bug
    fix).  Note: this was written using Python2.1's knee.py so will
    work only with 2.x
    pkg.tar.gz - which is a silly test package that I used for quick
    and dirty testing, this includes my_import.py and uses it.

pkg.tar.gz contains a reasonably deep nesting of packages 

$ ls -R pkg
__init__.py  a.py  my_import.py  sub/  test.py

__init__.py  b.py  c.py  subsub/

__init__.py  d.py

in d.py I do:

import a and import b.  So to test it you can do:

>>> import pkg.sub.c # sibling
a.a =  a
>>> import pkg.sub.b # not so deep nesting.
# look ma no prints!
>>> import pkg.sub.subusub.d # deep nesting
a.a =  a

Please do check it out and let me know what you folks think.  Now that
I have code to do what I meant, could this be made the default
behaviour for Python??



Prabhu Ramachandran			  MayaVi Data Visualizer
http://www.aero.iitm.ernet.in/~prabhu     http://mayavi.sf.net

More information about the Python-list mailing list