Python: import at the beginning of the main program and PEP 8

PEP 8 recommends importing modules at the beginning of programs.

Now I feel that importing some of them at the beginning of the main program (i.e. after if __name__ == '__main__') makes sense. For example, if the main program reads the arguments from the command line, I usually do import sysat the beginning of the main program: thus, it is sysnot necessary to import when the code is used as a module, since in this case there is no need to access the command line arguments.

How bad is this violation for PEP 8? Should I refrain from this? or would it be prudent to change PEP 8?

+5
source share
5 answers

I can’t tell you how bad it is.

However, I significantly improved the performance (response time, loading) for the web application by importing certain libraries only the first time I use it.

By the way, the following from PEP 8:

But the most important thing: to know when to be inconsistent - sometimes the style of leadership simply does not apply. When in doubt, use your best judgment. Take a look at other examples and decide which one looks better. And feel free to ask!

+8
source

In general, I do not think that with a late import of modules that may not be needed, there is not much harm.

sys , . , , sys script , . sys , Python, , ( sys).

+6

, , , , PEP .

+2

sys , . . , sys . , sys .

, , , , , . PEP 8 - , , , .

+2

.

.

"" - . , . , .

"" , .

  • "" if __name__ == "__main__". PEP-8. .

  • Try to limit the number of functions in your "main" scripts of the program. Try to save them before importand if __name__ == "__main__". If your main script is small, your import question goes away.

+2
source

All Articles