Add Python docstring to the beginning of anything in Emacs

Gergely Polonkai
Nov 30, 2016 :: 07:52

Now that I write Python code for a living, I write a lot of functions, classes, and modules. What I still tend to forget, and also find tedious, is adding docstrings. Unlike many developers, writing documentation is not an enemy of mine, but it usually comes to my mind when I finish implementation. The procedure, roughly, is this:

  • Decide where I am (in a function, in a class but not in one of its methods, or not inside such a block at all)
  • Go to the beginning of the thing
  • Insert """
  • Leave a blank line
  • Insert """

One of my mottos is if something takes more than one step and you have to do it more than twice, you should automate it after the first time. This puts a small(ish) overhead on the second invocation (when you implement the automation), but it usually worth the time.

Since I use Emacs for pretty much everything coding-related (and many more, but that’s the topic of a different post), I wrote a small function to do it for me.

There are still a lot of things to improve:

  • it always inserts double quotes (althoug I couldn’t show a use-case when single quotes are preferred)
  • it doesn’t check for an existing docstring, just happily inserts a new one (leaving the old one alone, but generating a syntax error this way)
  • it would also be nice if I could jump to the beginning of a file even from a class method. I guess I will use prefix keys for that, but I’m not sure yet.

You can bet I will implement these features, so check back soon for an updated version!

comments powered by Disqus

Gergely Polonkai is a systems engineer of a telco company, and also a freelancer self- and software developer.

He is learning about different IT subjects since the late 1990s. These include web development, application building, systems engineering, IT security and many others. He also dug his nose deeply into free software, dealing with different types of Linux and its applications, while also writing and contributing to some open source projects.

On this site he is writing posts about different stuff he faces during work (oh my, yet another IT solutions blog), hoping they can help others with their job, or just to get along with their brand new netbook that shipped with Linux.

“I believe one can only achieve success if they follow their own instincts and listen to, but not bend under others’ opinions. If you change your course just because someone says so, you are following their instincts, not yours.”