A smarter(?) package importer.

Rainer Deyke root at rainerdeyke.com
Wed Nov 7 01:46:52 EST 2001


"Prabhu Ramachandran" <prabhu at aero.iitm.ernet.in> wrote in message
news:mailman.1005111070.26322.python-list at python.org...
> 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.

Be careful you don't import the same module isn't loaded twice, or bad
performance and unreliable behavior will occur.  The correct behavior of
'import D' in module 'A.B.C' looks something like this:

1. Check 'sys.modules["A.B.D"]'.  If it does not exist, go to step 2.
  If it is 'None', go to step 3.  If it is not 'None', return it.
2. Try to load 'A.B.D' from file.  On success, set
  'sys.modules["A.B.D"]' to the module and return it.  On failure, set
  'sys.modules["A.B.D"]' to 'None' and go to step 3.
3. Check 'sys.modules["A.D"]'.  If it does not exist, go to step 4.
  If it is 'None', go to step 5.  If it is not 'None', return it.
4. Try to load 'A.D' from file.  On success, set
  'sys.modules["A.D"]' to the module and return it.  On failure, set
  'sys.modules["A.D"]' to 'None' and go to step 5.
5. Check 'sys.modules["D"]'.  If it does not exist, go to step 6.
  If it is 'None', raise an 'ImportError'.  If it is not 'None',
  return it.
2. Try to load 'D' from file.  On success, set 'sys.modules["D"]' to
   the module and return it.  On failure, set 'sys.modules["A.B.D"]'
   to 'None' and raise an 'ImportError'.

Notes:
 - 'sys.modules' is checked at each step before trying to load the module
from a file.  This is absolutely essential to prevent multiple copies of a
module being loaded.
 - Each module is stored in 'sys.modules' by its true name.  Again, this is
essential.
 - A value of 'None' in 'sys.modules' is used to cache failure.  This is not
essential, but it matches the current behavior of Python and it can give a
significant speed boost.


--
Rainer Deyke (root at rainerdeyke.com)
Shareware computer games           -           http://rainerdeyke.com
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor





More information about the Python-list mailing list