Python style: should I avoid commenting my import statements?
I'll try to make this as closed-ended of a question as possible:
I often find that I have a group of imports that go together, like a bunch of mathy imports; but later on I might delete or move the section of code which uses those imported items to another file. The problem is that I often forget why I was using a particular import (开发者_如何学运维for example, I use the Counter class very often, or random stuff from itertools.) For this reason I might like to have comments that specify what my imports are for; that way if I no longer need them, I can just delete the whole chunk.
Is it considered bad style to have comments in with my import statements?
Well, the beautiful thing about python is that it is (or should be) explicit. In this case, so long as you're not doing * imports, (which is considered bad practice), you'll KNOW whether an import is referenced simply by doing a grep for the namespace. And then you'll know whether you can delete it.
Allow me to also add a counterpoint to the other answers. 'Too much' commenting can indeed be bad practice. You shouldn't be adding redundant comments to code which is patently obvious as to its function. Additionally, comments, just like code, must be maintained. If you're creating excessive comments, you're creating a ton more work for yourself.
Comments are there to help explain/remind. If they are useful to you, use them. Also, tools such as pylint can help spot unneeded imports, as well as many other things.
It's not bad practice at all. It's better to have more comments than less comments. By documenting the reasons you are using certain imports, it will explain to to the reader of your code the reason you have them, and maybe the reader might see why you did something and be able to come up with a better way to do it.
You shouldn't really ever shy away from properly commenting your code.
I'm pretty sure if you're adding meaningful comments anywhere in the code, it can only be a plus.
I will sometimes add comments to strange/confusing imports, so I'd say go for it.
I wouldn't call it a bad practice. Comments are to provide clarity, and that is what you're trying to do. However, if you're getting confused on what imports are being used for, I would recommend determining if perhaps your modules are getting too big anyway.
精彩评论