Discussion forum for David Beazley

"inport" -- import by inlining

I have been experimenting with “inlining” the contents of python modules by renaming their variables and copying the contents directly into the importing script:

import thing
x = thing.func()

becomes:


… the code from thing.py

x = thing_func()

I do this rather brutally be prepending the filename to all variables in the imported module (using ast/astor) whether or not they are globals (and hence “intended” to be used by the importing script). I know this violates the last “commandment” in the Zen of Python, but on the other hand “Flat is better than nested” comes in at #5

Anyway, my question is as follows: is there a way to be a little less brutal about this, and only modify the variables that I know “at compile time” to be global (e.g. avoid renaming function args)? I guess the formal question is: what is the simplest way to unequivocally assign a variable its namespace (global vs. local) using ast? I didn’t see any write-up that addresses this question but it must be a common requirement… Note: I am not worried about “dynamically” generated access to variables through all of the indirect mechanisms that python provides, obviously those are beyond the scope of this little experiment.

Manor.