platform-specific overrides of functions and class methods (expanding on imputils demo code)

lkcl luke.leighton at googlemail.com
Mon Aug 17 15:03:57 CEST 2009


thought that people might like to know: i found also that imputil, the
standard python module, was lacking the necessary complexity in being
a substitute for the standard __import__ function.

the additions required were very simple:

    # note the addition of level=-1 which is ignored

    def _import_hook(self, fqname, globals=None, locals=None,
fromlist=None,
                           level=-1):

        .....

        # Grrr, some people "import os.path" or do "from os.path
import ..."
        if len(parts) == 2 and hasattr(top_module, parts[1]):
            if fromlist:
                return getattr(top_module, parts[1])
            else:
                return top_module

        # assume that the module has already been imported,
        # walk from top_module to find it.
        mod = top_module

        for k in parts[1:]:
            if not hasattr(mod, k):
                print "no mod", mod, k, parts
                mod = None
                break
            mod = getattr(mod, k)

        if mod:
            return mod

        # If the importer does not exist, then we have to bail. A
missing
        # importer means that something else imported the module, and
we have
        # no knowledge of how to get sub-modules out of the thing.
        raise ImportError, 'No module named ' + fqname

it's the module-walking that's been added: going from the "top"
module, looking for an attribute of the split-parts.  this code makes
the assumption that if top module already exists, and it has a sub-
module, and that has a sub-sub-module, and that has a sub-sub-sub-
module etc. then it is perfectly reasonable to return that pre-
existing, already-imported [sub-]+ module as the return result.

the reason why this had to be added is because comtypes.gen.{some
module} auto-generator relies on it, and calls __import__ *direct*.

if somebody would like to add this to the python bugtracker, as a
contribution, that would be great.  alternatively, you might like to
have a word with the python developers to get them to remove the
censorship on my contributions.

l.



More information about the Python-list mailing list