Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: imports at the beginning of the main program & PEP 8

The PEP 8 recommends that modules be imported 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 instance, if the main program reads arguments from the command line, I tend to do import sys at the beginning of the main program: this way, sys does not have to be imported when the code is used as a module, since there is no need, in this case, for command line argument access.

How bad is this infringement to PEP 8? should I refrain from doing this? or would it be reasonable to amend PEP 8?

like image 749
Eric O Lebigot Avatar asked Oct 14 '09 09:10

Eric O Lebigot


1 Answers

I can't really tell you how bad this is to do.

However, I've greatly improved performance (response time, load) for a web app by importing certain libraries only at the first usage.

BTW, the following is also from PEP 8:

But most importantly: know when to be inconsistent -- sometimes the style guide just doesn't apply. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don't hesitate to ask!

like image 90
Prody Avatar answered Oct 04 '22 19:10

Prody