Ok, I've tried to see see if this can be rewritten to be cleaner using astutil, but I couldn't find a way. You're really iterating over all imports, doing some calculations on the import path, and updating it if necessary. astutil would've been helpful if you had to rewrite some specific imports without having to iterate over them.