Postfix code completion

We have seen the general usage of PyCharm's smart code completion engine—looking at a suggestion list and choosing the item that you want. Here, we are considering using the engine for a specific purpose, that is, postfix code completion. Still working with the string_assert.py file from the previous example, we look at the suggestion list for variable b, and we enter a dot character after it.

Notice the first suggestion—if (if expr). If you are confused and don't know what the .if expression is in Python, you are completely right in thinking that. In fact, if you go ahead and select the option to complete the line of code, you will see that the code will be transformed into the following:

if b:

So, .if is just another way to express an if condition in PyCharm, but why is it necessary and desirable? Well, I know personally—and many might sympathize with me—that I would start an expression, say an if condition, by typing in the actual conditional expression (as opposed to the if keyword and then the expression), and only afterward move the caret back in front of that expression and add in the if keyword to correctly form a Python conditional statement.

This practice helps me organize my thoughts better, especially if the conditional expression is long and complex and consists of multiple components. But it requires me, again, to move the caret to the beginning of the expression and add the if keyword afterward. If I were to add together all the time I have spent doing this, I might feel compelled to give up this practice. Luckily, postfix code completion addresses this problem. When I've finished the conditional expression, I simply use the code completion feature, and the line of code will be formatted into a correct if statement.

Obviously, postfix code completion is not only limited to if statements. If you go to PyCharm's general settings, Editor | General | Postfix Completion, and scroll to the section for Python, you will be able to see a complete list of available expressions for postfix code completion. These are illustrated in the following screenshot:

Postfix code completion expressions in Python

You might notice that there are postfix completion options for other languages in that window as well (for example, TypeScript, JavaScript, and SQL). This goes to show that PyCharm realizes the different technologies that Python developers might use in integration with Python, and does its best to support a variety of technologies in the software. We, however, will not consider these options, and only focus on Python development specifically throughout this book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset