simple import hook

DevPlayer devplayer at gmail.com
Tue Nov 15 02:39:51 EST 2011


An alternative approach:
http://pastebin.com/z6pNqFYE

or:

# devplayer at gmail.com
# 2011-Nov-15

# recordimports.py

# my Import Hook Hack in response to:
# http://groups.google.com/group/comp.lang.python/browse_thread/thread/5a5d5c724f142eb5?hl=en
# as an initial learning exercise

# This code needs to come before any imports you want recorded
# usually just once in the initial (main) module
# Of course you can excluding the if __name__ == '__main__': demo code

# barely tested:
#    only tested with modules that had no errors on import
#    did not need/use/expect/try  reload()
#    ran with Python 2.7 on Win32
# create two fake modules moda.py and modb.py and stick some imports
in them

'''
Exerpt from PEP 302 -- New Import Hooks
...
Motivation:
    - __import__ gets called even for modules that are already in
      sys.modules, which is almost never what you want, unless you're
      writing some sort of monitoring tool.

Note the last two words.'''


#
=======================================================================
# place to save Collected imports
imported = []

# save old __builtins__.__import__()
__builtins__.__dict__['__old_import__'] =
__builtins__.__dict__['__import__']

# match __builtins__.__import__() function signature
def __myimport(name, globals={}, locals={}, fromlist=[], level=-1):
    global imported

    # I don't know why this works.
    __name__ = locals['__name__']
    __file__ = locals['__file__']
    __package__ = locals['__package__']
    __doc__ = locals['__doc__']

    # call original __import__
    module = __builtins__.__old_import__(name, globals, locals,
fromlist, level)

    # save import module name into namespace
    __builtins__.__dict__[name] = module

    tag = (name, __name__, __file__, __package__, module)

    # do not append duplicates
    if tag not in imported:
        imported.append( tag )

    return module

# store the new __import__ into __builtins__
__builtins__.__dict__['__import__'] = __myimport

# erase unneed func name
del __myimport
#
=======================================================================


# demo
if __name__ == '__main__':
    # import some random packages/modules
    import sys
    import moda        # a test module that does some other imports
    import modb        # a test module that does some imports
    from pprint import pprint

    # imported has name, __name__, __file__, __package__
    # show each import
    for n, __n, __f, __p, m in imported:
        print n
        print '   ', __n
        print '   ', __f
        print '   ', __p
        print
    del n, __n, __f, __p, m

    print 'recordimports.py'
    pprint(dir(), None, 4, 1)
    print

    print 'moda.py'
    pprint(dir(moda), None, 4, 1)
    print

    print 'modb.py'
    pprint(dir(modb), None, 4, 1)

    # print imported
    print



More information about the Python-list mailing list