imports inside main()?

Hi to all.

I make an independent file to read a configuration file with configparse, also i want this module to create a minimum config file while used standalone (with the if name == 'main' magic) .

I need to import another lib only for the sake of this use, is ok to put that import in the if, or the main function?

Minimal no funcional example

import normales tuff

def main():
       import io       # this is the import in interested
       do_the_thing()

def func1()
.
.
.

if __name__ == '__main__':
     import io             # this is my second option
     main()

Is there a standard practice in this cases?

Posted Feb 4, 2021, 12:48 PM UTC

17
fool59•

Consider putting this part on top

import normales

if name == 'main':

import io

2
panupatc•

You can import anywhere. Although it is recommended by the style guide to have all imports on the very top.

1
toastedstaplerimport itertools•

iirc general consensus is that all imports should go at the top so it's easy to see what is required. the only special case is if the library is particularly big and on some rarer code path. if it may never be needed and it's quite expensive to import then there may be no point importing it

1
vectorpropioOP•

But in the general usage that import wouldn't be used. Only for fallback config creation.

1
BobHogan•

You can do this, but I would recommend against it. Convention is to put all imports at the top of the file. I'd reserve stuff like this for compatibility reasons, e.g. you have to write some extra code that depends on a windows specific package to get your project to work on windows, then you could put the import into the compatibility function. But even then I'd still recommend putting the import at the top and either put it in if/else (check the platform script is running on) or a try/except (catch the import error if its not running on windows and that library is not available)

1

Not this way, it's not a common idiom and feels wrong:

def main():
       import io       # this is the import in interested
       do_the_thing()

​

But this way can be acceptable if the import should only happen when this script is run as a command, and it isn't completely unusual:

if __name__ == '__main__':
     import io             # this is my second option
     main()
1
vectorpropioOP•

Thanks.

But this way can be acceptable if the import should only happen when this script is run as a command

Yes, that's the only case, and i wouldn't expect it to be used often.

1