Tutorial

How To Create a Python Class Generator for VS Code

Published on December 12, 2019
How To Create a Python Class Generator for VS Code

###Introduction If you hate stubbing out Python classes, here’s how you can create an extension in Visual Studio Code to do it for you. In this article, you’ll see how to create that extension. We will use several techniques to do so.

  • Prompting User Input
  • Array Map and Join Functions
  • ES6 Template Literals
  • Writing to the File System

You’ll create a new extension, prompt the user for input, convert the input to a string that represents the new class file, and write out the result.

Python Class Generator

Creating the Project

To get started with developing Code extensions, you’ll need two different NPM packages installed, “yo” and “generator-code”.

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.

Select JavaScript or TypeScript

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

Opening the new project in VS Code

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

Viewing the created files

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

Renaming the extension command name

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

Renaming the activation event and command

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

Updating the title

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”.

Using the new command

And you should see the “Hello World” message.

New command started successfully

Prompt the User for Input

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 they want 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;

We want to let the user input as many properties as they want 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") {
  properties.push(property);
  count++;
  property = await vscode.window.showInputBox({
    prompt: `Property #${count}? ('done' when finished)`
  });
}

Rerun your extension, enter in valid inputs, and print the user’s info to be sure it looks right.

Create the Class Content String

Now, we start to take the user’s 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`)
  .join("");

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
  .map(
    property => `\tdef get_${property}(self):\n\t\treturn self.${property}\n\n`
  )
  .join("");

The last thing we want to create is the string function that will tell Python how to print this object. Again, we use the map function to convert each property by printing the name of the property and then its 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 off the last 11 characters by using splice.

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

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

const classString = `${classDefinition}
    ${constructorDefinition}
        ${constructorAssignments}
${classGetters}
${dunderStrString}`;

Create a log statement and run this again to make sure your class string looks good.

Creating the Class File

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. You can get a reference to open directories by vscode.workspace.workspaceFolders. Then, we get the first one from the resulting array, grab its URI, and convert it to a string. The resulting path string included a prefix, so we strip that out by splitting on a colon and grabbing what comes after the colon.

const folderPath = vscode.workspace.workspaceFolders[0].uri
  .toString()
  .split(":")[1];

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 you want to create. “Person” in this case.

Enter the Person class

Then enter your properties, “name” first.

Enter the name property

Then “age”.

Enter the age property

Then “done” to finish.

Enter "done" to finish

The file is successfully created.

The file is successfully created

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

Viewing the class in VS Code

Conclusion

In this tutorial, you’ve created an extension to solve a specific problem. It provides an opportunity to learn more about VS Code, and it’s also something that others will benefit from.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.