[Tutor] sharing a small script someone may find of use

Peter Otten __peter__ at web.de
Sat Aug 13 10:22:57 EDT 2022


On 13/08/2022 02:53, Nathan Smith wrote:

> I wanted to share this small script I wrote today with the list as I
> thought 1, someone might find it useful, and 2, feedback! :)
>
>
> Use case: This script can be used to identify which modules are holding
> things up at the import stage and give you a rough estimate as to how
> long your imports are taking for a program during start up.
>
> Limitations: Doesn't like from . import x, although this can be resolved
> easily with a minor edit.
>

>      if(x.startswith ("import") or x.startswith("from")):
>          word=x.split(" ")
>          if(word[1] not in modules):
>              modules.append(word[1].strip("\n"))

> I know I'm very paren happy, it's a habit from coding in a different
> language that requires it :) But any other feedback welcome!

You are treating Python code as text and inspect it with standard string
processing methods.

There is an alternative, though. The ast module allows you to convert
code into a tree of objects that you can search for Import nodes.
This may look a bit harder in the beginning, but it already knows about
docstrings and comments, and can even be used to modify the original
source in ways that go beyond an editor's search-and-replace capabilities.

A rudimentary example:

import ast


class ImportVisitor(ast.NodeVisitor):
     def __init__(self):
         self.imports = set()

     def visit_Import(self, node):
         for alias in node.names:
             self.imports.add(alias.name)

     def visit_ImportFrom(self, node):
         "to be done"


def find_imports(source):
     tree = ast.parse(source)
     visitor = ImportVisitor()
     visitor.visit(tree)
     return visitor.imports

 >>> find_imports("""
... "import ignored"
... import foo.bar
... print(42)
... import ham, spam
... def f():
...     import jam
""")
{'foo.bar', 'ham', 'spam', 'jam'}




More information about the Tutor mailing list