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:
- Create an empty file and manually write the test class
- Copy/paste content from an existing file, remove unnecessary code, and adapt it to test a new scenario
- 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!

Early in my career, I specialized in the Python language. Python has been a constant in my professional life for over 10 years now. In 2018, I moved to London where I worked at companies of various sizes as a Python developer for five years. In parallel, I developed my activity as a Mentor, to which I now dedicate myself full-time.