Simran Madhok
2 min readMar 26, 2023

--

How to generate Python DocString with ChatGPT OpenAPI

Photo by Jonathan Kemper on Unsplash

Writing documentation for your Python code can be a time-consuming and tedious task, but it’s an all-important part of developing maintainable and reusable code.

However, with the recent ChatGPT advancements, you can now use this AI-powered language model to automatically generate documentation for your Python functions and modules using OpenAPI.

The free plan provides up to 5,000 API requests per month, with a limit of 1,000 requests per day; and it offers excellent options for both non-technical persons and developers alike.

Pre-requisuites

pip install openai

How to?

Step 1. Define your Python function

Say you have a Python function that calculates the average of two numbers for a function named “avg” that takes two arguments -

def avg(a, b):
return (a + b)/2

Step 2. Import OpenAPI packages

import openai
import re

Step 3. Setup OpenAPI credentials

openai.api_key = "PLACE_YOUR_API_KEY_HERE"

Step 4. Define a prompt for the ChatGPT Model

Define a prompt including the name and docstring of the Python function.

We then use the openai.Completion.create() method to generate the documentation, specifying the language model, the prompt, and other parameters.

prompt = f"Generate Python documentation for the following function:\n\n{avg.__name__}{avg.__doc__}"
response = openai.Completion.create(
engine="text-davinci-002",
prompt=prompt,
max_tokens=100,
n=1,
stop=None,
temperature=0.5,
)

Step 5. Generate documentation

Finally, we extract the generated documentation from the API response and print it to the console.

documentation = response.choices[0].text
documentation = re.sub(r"\n", " ", documentation).strip()

print(documentation)

By leveraging the power of AI, you can save time and effort on maintaining documentation across all your extensive Python modules.

Comment down below on more such use cases achievable with the ChatGPT OpenAPI Model.

Other articles that helped me along the way

--

--

Simran Madhok

Software Engineer — Python Full Stack Developer — Mobile Application Development