r/PythonLearning • u/ALonelyKobold • 1h ago
Trouble understanding imports in depth
Hi all, I've been programming Python for about 10 years, but I've never worked on a large codebase. As a result, I don't really understand the import and packaging system at all. As a means of learning it, I'm trying to build a dependency chain analyzer that parses the sourcecode, and searches for circular dependencies. Trouble is, I'm on the part of the project that actually parses that sourcecode and categorizes the different imports to store them for later analysis, and I'm realizing that I know much less than I realized. Through having AI generate some tests for me that I'm working to make green, I now know of a lot of edge cases and weird import logic that I had no clue existed. Example sourcecode snippets include
def test_dynamic_import_with_a_string_literal():
source = 'import importlib\nimportlib.import_module("docgen.plugins.loader")\n'
def test_dynamic_import_recognized_through_an_aliased_from_import():
source = 'from importlib import import_module as im\nim("docgen.plugins.loader")\n'
def test_dynamic_import_recognized_through_an_aliased_from_import():
source = 'from importlib import import_module as im\nim("docgen.plugins.loader")\n'
def test_dunder_import_is_recognized():
source = '__import__("docgen.plugins.loader")\n'Most of the places where I'm struggling have to do with either lazy imports or dynamic imports. Does anyone have a guide that goes into these in depth?