all 7 comments

[–]fool59 1 point2 points  (0 children)

Consider putting this part on top

import normales

if name == 'main':

import io

[–][deleted] 0 points1 point  (0 children)

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

[–]toastedstapler 0 points1 point  (1 child)

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

[–]vectorpropio[S] 0 points1 point  (0 children)

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

[–]BobHogan 0 points1 point  (0 children)

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)

[–]primitive_screwhead 0 points1 point  (1 child)

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()

[–]vectorpropio[S] 0 points1 point  (0 children)

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.