Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I track python imports [closed]

Tags:

I have cyclical import issues adding some new code to a very large app, and I'm trying to determine which files are the most likely causes for this. It there any way to track which files import which files? I did a bit of looking and found the python trace command, but it's just showing a bunch of activity in the main python libraries.

I'm basically looking for an app that will show me something like:

App1 >>imports>> App2,App3.method App2 >>imports>> App3,etc 

I could just look through all of my files, but I'd rather not, it's a big app.

like image 749
Jeff Avatar asked Nov 28 '09 00:11

Jeff


People also ask

How do you check if a module is already imported?

Use: if "sys" not in dir(): print("sys not imported!")

Where do Python imports go?

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

How do I know if a Python package is available?

Check package version with conda command: conda list. If you have built a Python environment with Anaconda, conda list will list the packages installed in the current virtual environment. If the environment is not activated, use conda list -n <environment name> .

How do I import a tracker into Python?

Move the module to any folder in Python Path: Python path can be found out by entering import sys;print sys. path in Python terminal. It will print out many locations. Move /usr/local/lib/python2.


1 Answers

Here's a simple (and slightly rudimentary;-) way to trace "who's trying to import what" in terms of module names:

import inspect import __builtin__ savimp = __builtin__.__import__  def newimp(name, *x):   caller = inspect.currentframe().f_back   print name, caller.f_globals.get('__name__')   return savimp(name, *x)  __builtin__.__import__ = newimp 

which gives, for example (having saved this as tracimp.py):

$ python -c 'import tracimp; import email; import sys; import email.mime' email __main__ sys email email.mime email sys __main__ email.mime __main__ 

As you see, one specific characteristic of "wrapping" the __import__ built-in is that it won't be silenced by the fact that a module being imported is already in sys.modules: since taking care of that is one of __import__'s jobs, our wrapper gets called for both modules "being loaded for the first time" and ones that are just going to get fetched from sys.modules because they were already imported previously. This should come in really handy when you're trying to diagnose circular imports (it boils down to finding loops in the directed graph whose edges are identified by the two module names -- imported and importer -- which this simple approach is printing on each output line).

like image 63
Alex Martelli Avatar answered Sep 25 '22 02:09

Alex Martelli