Is there a package to move import statements from a function to the top of the file?

It is quick to add import statements inside a function during development, but it is better to move the imports to the top of the file while publishing it. Is there any package to automatically do this job?

Source:

def aa():
    import os
    print(os.getcwd())

if __name__ == "__main__":
    aa()

Expected:

import os

def aa():
    print(os.getcwd())

if __name__ == "__main__":
    aa()

It is quick to add import statements inside a function during
development,

I add them to the top during development. A lint tool can whinge at me
later about any which are unused when the code’s “ready”.

but it is better to move the imports to the top of the file while
publishing it. Is there any package to automatically do this job?

I don’t know off hand. There’s a package called isort for sorting the
top level imports but it probably won’t move imports out of functions
because sometimes we leave them inside function for specific reasons
(typically to keep an imported name private or to do what would
otherwise be a circular import).

Possibly your editor can do it? In mine (vim) I’d go:

 :g/^  *import /m1

as a quick hack, then tidy up after.

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like

Smart hack, thanks :+1:

As @cameron writes, putting imports into functions is used in practical cases to avoid circular import. Therefore, automatically moving imports to the top of the file can destroy the code.

PyCharm has an “optimize imports” feature: