question 220 Modules & Packages · hard
In which order do a package's modules depend on each other?
A refactoring tool needs to know which modules of a package depend on which, so it can move them without breaking imports. Read the package's files (without importing them) and put its modules in dependency order: every module after all the sibling modules it imports.
Function
import_order(folder)Modulesevery
*.py file in folder except __init__.py, named by its stemDependenciesa line of the form
from .name import … (leading spaces allowed) means the module depends on sibling name; siblings that don't exist and all other imports are ignoredOrderrepeatedly place the alphabetically first module whose dependencies are all already placed
Returnsthe list of module names in that order
Raises
ValueError when some modules can never be placed (an import cycle)Examples
callimport_order('shopkit')returns['money', 'tax', 'pricing', 'report']
callimport_order('flat')returns['a', 'b']
callimport_order('loop')raisesValueError