Library import inside or outside functions

Asked

Viewed 88 times

0

I was wondering if it is correct to import libraries within functions? Or it is better to import the library in the file that the function is called, but the function will only work if the library that the function needs has been previously imported.

2 answers

4

According to PEP-8:
"Imports should always be placed at the top of the file, right after any comments or docstrings, and before constants or global. "
Follow the link with more information about the style guide:

Style Guide

2


Although there are cases where importing the library into a function makes sense, the most common and recommended is that the library be imported into the file header where the library functions are used.

It is usually evident when you need to import a library into a function. If not evident, you should probably import it in the header.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.