简体   繁体   中英

Is there a way to automatically verify all imports in a Python script without running it?

Suppose that I have a somewhat long Python script (too long to hand-audit) that contains an expensive operation, followed by a bunch of library function calls that are dependent on the output of the expensive operation.

If I have not imported all the necessary modules for the library function calls, then Python will error out only after the expensive operation has finished, because Python interprets line by line.

Is there a way to automatically verify that I have all the necessary imports without either a) manually verifying it line by line or b) running through the expensive operation each time I miss a library?

Another way to put that question is whether there is a tool that will do what the C compiler does with respect to verifying dependencies before run time.

No, this is not possible, because dependencies can be injected at runtime.

Consider:

def foo(break_things):
    if not break_things:
        globals()['bar'] = lambda: None

long_result = ...
foo(long_result > 0)
bar()

Which depending on the runtime value of long_result , may give NameError: name 'bar' is not defined .

There is a module called snakefood :

Generate dependency graphs from Python code

It uses the AST to parse the Python files.

This is very reliable, it always runs. No module is loaded. Loading modules to figure out dependencies is almost always problem, because a lot of codebases run initialization code in the global namespace, which often requires additional setup. Snakefood is guaranteed not to have this problem (it just runs, no matter what).

You can get a list of imports by calling sfood-imports <script.py> . Then you can import each module in the list one by one and see if it throws ImportError .

Or, just use pylint . Quote from docs:

Error detection

checking if declared interfaces are truly implemented

checking if modules are imported

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM