Creating a Python Class Generator for VS Code

Creating a Python Class Generator for VS Code

In this article, let's walk through how I created an extension in Visual Studio Code

In this article, let's walk through how I created an extension in Visual Studio Code

My motto...when you have a problem, do something about. I hated stubbing out Python classes so I created an extension in Visual Studio Code to do it for me. In this article, let's walk through how I created that extension. We will use several techniques to do so.

Table of Contents

  • TLDR
  • Creating the Project
  • Prompt the User for Input
  • Create the Class Content String
  • Creating the Class File
  • Run It
  • Recap
  • Prompting User Input
  • Array Map and Join Functions
  • ES6 Template Literals
  • Writing to the File System

Create a new extension, prompt the user for input, convert the input to a string that represents the new class file, and write out tha

Check out the end result HERE.

Creating the Project

To get started with developing Code extensions, you’ll need two different NPM packages installed, “yo” and “generator-code”. If you’re looking for a little more background on creating VS Code extensions, check out Creating Your First Visual Studio Code Extension!

To generate your project, run the following command.

yo code

This will follow up by asking you several questions about your project. Choose either JavaScript or TypeScript for your extension.

After answering all of the questions, open the newly created project in Code.

You’ll have a several different files created for you, the two most important are the package.json and extension.js files.

Start by opening the extension.js file. Then, rename the extension command name to “createPyClass”.

Then, in the package.json file, rename the activation event and command to match the name of the command.

Update the title as well, which is what the user will type to activate the command.

To run the extension, open the debug panel (looks like a bug) and press play. This will open up a new instance of VS Code. Open the command prompt (Command+Shift+P on Mac and Control+Shift+P on Windows) and type “Create Python Class”.

And you should see the “Hello World” message.

Prompt the User for Input

Here comes the tricky part. We need to prompt the user for input about the class (class name and properties) and convert that input into a string that we can write to the new class file.

Let’s start by ensuring the user has a folder currently open. If not, we don’t have a place to write the new class file to. If the user does not have a folder open, we show an error message and return.

if (!vscode.workspace.workspaceFolders) {
  return vscode.window.showErrorMessage(
    "Please open a directory before creating a class."

Now, we can ask the user for the name of the class he/she wants to create. If the user, for some reason, closes the input prompt (by hitting escape) we return.

const className = await vscode.window.showInputBox({
  prompt: "Class Name?"

if (!className) return;

Now, a bit of a tricky part. We want to let the user input as many properties as he/she wants to. For this we prompt initially for a property, then run a while loop retrieving properties until the user enters ‘done’.

let count = 1;
let property = await vscode.window.showInputBox({
  prompt: `Property #${count}? ('done' when finished)`
const properties = [];
while (property != "done") {
  property = await vscode.window.showInputBox({
    prompt: `Property #${count}? ('done' when finished)`

This might be a good point to rerun you extension, enter in valid inputs, and print the user’s info just to be sure it looks right.

Create the Class Content String

Now, we start to take the users input to generate the content of the class. Let’s start by creating the class definition line as well as the constructor definition.

const classDefinition = `class ${className}:`;
const constructorDefinition = `def __init__(self, ${properties.join(", ")}):`;

Then, we can create the constructor assignments lines. This is where the user will initialize variables on itself, using the values of the constructor parameters. For this, we use map (as we will from now on) to convert each of the property inputs in some way.

const constructorAssignments = properties
  .map(property => `self.${property} = ${property}\n\t\t`)

Now, for each property, we create a getter function. Again, we use map to convert each property into a string that represents its getter.

const classGetters = properties
    property => `\tdef get_${property}(self):\n\t\treturn self.${property}\n\n`

And the last thing we want to create is the string function that will tell Python how to print this object. This one is pretty tricky. Again, we use the map function to convert each property by printing the name of the property and then it’s value.

Notice that in the map return value, we are adding a comma and a plus. This means for the last property, we would be adding unnecessary characters at the end. For this reason, we convert the resulting array to a string and chop of the last 11 characters by using splice.

const dunderStrString = `\tdef __str__():\n \t\treturn ${properties
  .map(property => '"' + property + ': "' + " + " + property + ' + " , " + ')
  .slice(0, -11)}`;

Let’s take this individual pieces and put them all together!

const classString = `${classDefinition}

I would recommend creating a log statement and running this again to make sure your class string looks good!

Creating the Class File

Whew, that was a lot, but it gets easier from here. Now, we need to write that string to a new file. To work with files, we need to import the “fs” and “path” modules from Node at the top of the page.

const fs = require("fs");
const path = require("path");

Then, we need to get the path for the user’s currently open directory. This was a bit tricky for me. You can get a reference to open directories by vscode.workspace.workspaceFolders. Then, we get the first one from the resulting array, grab it’s uri, and convert it to a string. The resulting path string included a prefix, so we strip that out by splitting by a colon and grabbing what comes after the colon.

const folderPath = vscode.workspace.workspaceFolders[0].uri

Now we can use the fs module, the folder path, and the name of the class file, to write the class string to our new file!

fs.writeFile(path.join(folderPath, `${className}.py`), classString, err => {});

We can take it one step further by providing the user some feedback based on whether or not the write file was successful.

fs.writeFile(path.join(folderPath, `${className}.py`), classString, err => {
  if (err) {
    vscode.window.showErrorMessage("Something went wrong");
    return console.log(err);
  vscode.window.showInformationMessage(`${className} Class created.`);

Run It

Either refresh your debugging instance or start again by following the steps above. With the debug instance of VS Code open, run your “Create Python Class” command again. Then, enter the name of the class your want to create. “Person” in this case.

Then enter your properties, “name” first.

Then “age”.

Then “done” to finish.

Hopefully, yours says that the file was successfully created.

Then, double check your file was actually created and it looks good!


Again, if you struggle with something in your development process, work to improve it. In this case I created an extension to solve a specific problem I had. It’s also something that others will benefit from as well. Not to mention, it was a great learning opportunity!

python visual-studio

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Fast, feature-rich language support for Python in Visual Studio Code | Python

We are excited to announce Pylance, our fast and feature-rich language support for Python! Pylance is available today in the Visual Studio Code marketplace. Pylance depends on our core Python extension and builds upon that experience, for those of you who have already installed it.

Basic Data Types in Python | Python Web Development For Beginners

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Python in Visual Studio Code

Python in Visual Studio Code

Visual Studio Code For Python Development

This video 'Visual Studio Code For Python Development' will help you understand how you can use the Python extension to write python code in the visual studio code editor.

Getting Started with Python in Visual Studio Code

Python is one of the most popular and easy to learn languages, which is why it is often one of the first languages you learn. Let’s see how to work with and run Python inside of Visual Studio Code!