Pycharm file template == Productivity

Written by

I just discovered how to create a PyCharm file template, which is very useful for saving time.

As developers, we are often required to create new files with a structure similar to existing ones in the codebase. To improve readability and ensure the long-term maintainability of the project, new files should be written in a similar and consistent way.

For example, when I create new unit tests, my file is usually structured into several sections:

  • Definition of my test class
  • Preconditions for my tests
  • A test that validates the expected behavior
  • A test that checks for an expected error
  • Class name added to __all__

There are three ways to create this new test file:

  1. Create an empty file and manually write the test class
  2. Copy/paste content from an existing file, remove unnecessary code, and adapt it to test a new scenario
  3. Create a file based on a template

Option number 3 clearly wins. 👏

How to create a template with PyCharm?
Go to:
PyCharm Menu → Preferences → Editor → File and Code Templates

In this template, I use the variable ${name}, which will be defined by the user before generating the new file.

To format a variable (e.g. capitalize a string or convert it to lowercase), the string methods available in Java can be used.

Once the template is created, it becomes available from the file creation menu.

⭐️ This concludes the tutorial on creating a file template with PyCharm. I hope you find it useful. Cheers!