Python
Programming
Modules
Import
Coding Tips

How to list imported modules?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

To "list imported modules" in Python, you first need to decide what you mean by imported. You might want the modules currently loaded in a running interpreter, or you might want the import statements that appear in a source file without executing that file.

Listing Modules Already Loaded at Runtime

Python keeps a registry of loaded modules in sys.modules. If your code has already run and you want to inspect what the interpreter has imported so far, this is the simplest option.

python
1import sys
2import json
3import math
4
5loaded = sorted(sys.modules.keys())
6
7for name in loaded[:20]:
8    print(name)
9
10print("total loaded:", len(loaded))

This shows everything loaded in the current process, including modules imported indirectly by Python itself or by libraries you imported earlier.

If you only care about top-level package names:

python
1import sys
2
3top_level = sorted({name.split(".")[0] for name in sys.modules})
4print(top_level)

That makes the list easier to scan, but it is still a runtime view, not a static analysis of your file.

Listing Import Statements from a Python File

If you want to know what a file imports without executing it, parse the file with ast. This is safer than using exec or importing the file just to inspect its dependencies.

python
1import ast
2from pathlib import Path
3
4def list_imports(path):
5    source = Path(path).read_text(encoding="utf-8")
6    tree = ast.parse(source, filename=path)
7    modules = []
8
9    for node in ast.walk(tree):
10        if isinstance(node, ast.Import):
11            for alias in node.names:
12                modules.append(alias.name)
13        elif isinstance(node, ast.ImportFrom):
14            module = "." * node.level + (node.module or "")
15            modules.append(module)
16
17    return sorted(set(modules))
18
19print(list_imports("example.py"))

This works for statements such as:

python
1import os
2import pandas as pd
3from pathlib import Path
4from .utils import clean_data

The output tells you which modules the source references, even if the file would fail at runtime.

Runtime Listing and Static Listing Answer Different Questions

This distinction matters a lot.

sys.modules answers, "What has this interpreter loaded already?"

ast answers, "What import statements appear in this source code?"

Those answers are not always the same. A file may contain conditional imports, imports inside functions, or imports that fail at runtime. A running session may also contain many modules that your file never imports directly.

For example:

python
if False:
    import numpy

Static analysis sees numpy in the file. Runtime inspection does not, because the branch never executes.

Listing Third-Party Packages Is a Different Task

Sometimes people ask this question when what they really want is the environment's installed packages. That is not the same as imported modules.

Installed packages can be listed with tools such as:

bash
python -m pip list

or:

bash
python -m pip freeze

Those commands show what is installed in the environment, not what a given script imports.

A Practical Utility Script

If you want a reusable command-line tool for static inspection, this is a solid starting point:

python
1import ast
2import sys
3from pathlib import Path
4
5def list_imports(path):
6    source = Path(path).read_text(encoding="utf-8")
7    tree = ast.parse(source, filename=path)
8    imports = set()
9
10    for node in ast.walk(tree):
11        if isinstance(node, ast.Import):
12            for alias in node.names:
13                imports.add(alias.name)
14        elif isinstance(node, ast.ImportFrom):
15            name = "." * node.level + (node.module or "")
16            imports.add(name)
17
18    return sorted(imports)
19
20if __name__ == "__main__":
21    for module_name in list_imports(sys.argv[1]):
22        print(module_name)

Run it like this:

bash
python list_imports.py your_script.py

That gives you a quick, repeatable way to inspect source dependencies without running application code.

Common Pitfalls

The most common mistake is mixing up loaded modules with installed packages. sys.modules is about the current interpreter session, while pip list is about the environment.

Another issue is assuming static analysis captures dynamic imports. Calls such as importlib.import_module(...) may not appear as plain import statements, so an ast walk will not necessarily catch them.

Relative imports can also be confusing. A statement like from .helpers import x is valid in a package, but the raw output may appear as a relative module path rather than a fully resolved absolute name.

Finally, avoid importing unknown files just to discover their imports. That can execute arbitrary code and produce side effects.

Summary

  • Use sys.modules to list what the running interpreter has already loaded.
  • Use ast to list import statements from a source file without executing it.
  • Do not confuse imported modules with installed packages.
  • Static analysis will miss some dynamic import patterns.
  • Choose the method that matches the question you are actually trying to answer.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.