runtime
359 / 500
question 359 Memory & Python Internals · hard

Find each function's hidden global dependencies

Before splitting a big module into smaller ones, a team wants to know which module-level names each function secretly depends on (globals it reads, not parameters). Write hidden_dependencies(source): compile the module's source without running it, find each top-level function's code object, and list the globals it reads with LOAD_GLOBAL, leaving out built-ins such as len and print.

Functionhidden_dependencies(source)
sourcethe text of a module whose top-level defs are to be analysed
Returnsa dictionary from function name to a sorted list of the distinct non-built-in globals it reads
Toolscompile(source, "<module>", "exec"); a module's functions are code objects in its co_consts (they have co_name); a name is built in when hasattr(builtins, name)
Examples
callhidden_dependencies("TAX = 0.0825\ndef price_with_tax(price):\n return round(price * (1 + TAX), 2)\ndef label(order):\n return FORMAT.format(order['id'], price_with_tax(order['total']))\n")returns{'price_with_tax': ['TAX'], 'label': ['FORMAT', 'price_with_tax']}
callhidden_dependencies('def total(prices):\n return sum(prices)\n')returns{'total': []}
callhidden_dependencies('RATES = {}\ndef convert(amount, currency):\n return amount * RATES[currency] * RATES[currency]\n')returns{'convert': ['RATES']}

Loading your progress…

Find each function's hidden global dependencies — Python practice · Runtime