runtime
220 / 500
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.

Functionimport_order(folder)
Modulesevery *.py file in folder except __init__.py, named by its stem
Dependenciesa 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 ignored
Orderrepeatedly place the alphabetically first module whose dependencies are all already placed
Returnsthe list of module names in that order
RaisesValueError 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

Loading your progress…

In which order do a package's modules depend on each other? — Python practice · Runtime