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?
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: