2002-11-17

… and your little snake, too!

I did a little digging based on the Perl technique I described yesterday, and I think there is a similiar way to hook into the Python mechanism so that you don't have to do anything special in your module to get the desired behavior.

Here is a simple test module, which I have stored in the file "FOO.px":

  def foo():
    print "FOO.foo()"

And, here is a main program that wants to import that module, which I have stored in the file "tryme.py":

  #!/usr/bin/python
  import sys
  import PX
  from FOO import foo
  foo()

The magic comes from the 'import PX' statement, which installs the special import hook:

  #!/usr/bin/python
  import imputil, sys
  imputil.ImportManager().install()
  class PX(imputil.Importer):
    def get_code(self, parent, modname, fqname):
      return 0, open(modname + '.px', 'r'), { }
  sys.path.insert(0, imputil.BuiltinImporter())
  sys.path.insert(0, PX())

Now, this implementation is not robust as the Perl implementation, but it does work to demonstrate the technique.

I believe that the need for 'import PX' in any given file can be relieved by using the Python site.py mechanism, although I haven't tried it myself. If so, then the modules that appear in the job automation system could look just like any other Python module, happily importing modules that in reality are not coming from the local file system...

NOTE: There are some interesting examples here.

No comments: