Don't setdefault in mymf.import_module if import_hook hasn't been run. master
authorW. Trevor King <wking@drexel.edu>
Sun, 9 Jan 2011 05:08:30 +0000 (00:08 -0500)
committerW. Trevor King <wking@drexel.edu>
Sun, 9 Jan 2011 05:08:30 +0000 (00:08 -0500)
It raised exceptions trying to get _last_caller.__name__ when
_last_caller was None.

Also:
* Add logger to py2depgraph
* Disable (for now) ModuleFinder's internal debugging.

py2depgraph.py

index a733fc484d8d4a8a11b48dc6e2aa8eb461b0fcf3..fa1b9304c01bac293cdf2b44e8c4775bbb99f2ce 100755 (executable)
 """Extract a tree of module imports from a Python script.
 """
 
 """Extract a tree of module imports from a Python script.
 """
 
+import logging
 import modulefinder
 
 import modulefinder
 
+LOG = logging.getLogger('py2depgraph')
+LOG.setLevel(logging.DEBUG)
+_STREAM_HANDLER = logging.StreamHandler()
+_STREAM_HANDLER.setLevel(logging.CRITICAL)
+_STREAM_HANDLER.setFormatter(
+    logging.Formatter('%(levelname)s - %(message)s'))
+LOG.addHandler(_STREAM_HANDLER)
+
+
 class mymf(modulefinder.ModuleFinder):
     def __init__(self,*args,**kwargs):
         self._depgraph = {}
 class mymf(modulefinder.ModuleFinder):
     def __init__(self,*args,**kwargs):
         self._depgraph = {}
@@ -42,10 +52,12 @@ class mymf(modulefinder.ModuleFinder):
             return modulefinder.ModuleFinder.import_hook(self,name,caller,fromlist, level)
         finally:
             self._last_caller = old_last_caller
             return modulefinder.ModuleFinder.import_hook(self,name,caller,fromlist, level)
         finally:
             self._last_caller = old_last_caller
+        LOG.debug('after import_hook(%s, %s, %s, %s), last_caller is %s'
+                  % (name, caller, fromlist, level, self._last_caller))
 
     def import_module(self,partnam,fqname,parent):
         r = modulefinder.ModuleFinder.import_module(self,partnam,fqname,parent)
 
     def import_module(self,partnam,fqname,parent):
         r = modulefinder.ModuleFinder.import_module(self,partnam,fqname,parent)
-        if r is not None:
+        if None not in [r, self._last_caller]:
             self._depgraph.setdefault(self._last_caller.__name__,{})[r.__name__] = 1
         return r
 
             self._depgraph.setdefault(self._last_caller.__name__,{})[r.__name__] = 1
         return r
 
@@ -69,8 +81,13 @@ if __name__=='__main__':
 
     options,args = p.parse_args()
 
 
     options,args = p.parse_args()
 
+    log_level = logging.CRITICAL - 10*options.verbose
+    _STREAM_HANDLER.setLevel(log_level)
+
     script = args[0]
 
     script = args[0]
 
-    mf = mymf(path=sys.path[:], debug=options.verbose, excludes=[])
+    debug = options.verbose
+    debug = 0
+    mf = mymf(path=sys.path[:], debug=debug, excludes=[])
     mf.run_script(script)
     pprint({'depgraph':mf._depgraph,'types':mf._types,'paths':mf._paths})
     mf.run_script(script)
     pprint({'depgraph':mf._depgraph,'types':mf._types,'paths':mf._paths})