Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the application style of Pycharm code?

2025-01-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "Pycharm code application style is what", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn "What is the application style of Pycharm code"!

1. Theme

This tutorial focuses on how to create a Python project and make it Pycharm-style. You will see that Pycharm makes your source code very clean and beautiful, with appropriate indentation, spaces, etc., so Pycharm is also a tool for code quality control.

This tutorial doesn't cover programming in Python. For more information about Python programming, see Python Programming.

2. Preparations

Before we begin, please confirm the situation:

(1) Pycharm 2.7 or later software installed

(2) A Python project has been created (File→New Project). For details, see Pycharm New Project File.

(3) Two directories have been added under Project: src and test_dir (File→New or Alt+Insert). For details, refer to Pycharm New Project File.

(4) The corresponding Python file has been added to the project directory (File→New or Alt+Insert). For details, refer to Pycharm New Project File.

3. Highlight mode of code error

Open a new Python file for editing (F4), which by default has two lines of code: author name and project name. These two lines of code appear because Python files are created based on file templates, so these two variables are predefined.

Next type the keyword class, and as you start typing, Pycharm's spelling-hinting mechanism immediately lists candidates to help you complete the code:

This red wavy line marks the expected position of the next code input, in this case a pre-input definer. Type the class name Solver and the wavy red line will move after the class name. If you hover your mouse pointer over the wavy line, you will see an error message ("Colon expected"), and of course, the red sign on the right scroll bar will give the same error message.

OK, type colon, enter. According to Python code style standards, we need to define the next class declaration, but we can cancel it by typing spaces.

4. Focus on PEP8 code style check

However, these warning reminders are invisible by default, so the first thing you need to do is raise their priority for display. Click the Settings button, then on the Inspections page of the Settings/Preferences dialog box, type PEP8 to find all relevant options, and select the warning option in the corresponding drop-down menu:

Click Apply to close the dialog box and return to the source code editing interface.

5. Detailed explanation of PEP8 code style

Ptcharm is now able to display its code specifications correctly, ensuring the integrity of the code format you write. Next, when we type the next statement (e.g. def demo(self,a,b,c):), Pycharm will report the current formatting problem according to PEP8's code specification mechanism.

As you can see, Pycharm sets the PEP8 specification it supports as the default regular Python code format standard. If you open the list of observations (Ctrl+Alt+S→Inspections), you can see that Pycharm has loaded the pep8.py tool into your code to pinpoint your stylistic problems.

6. Code check and related settings

By the way, if you look closely at the default settings for inspection profile on the Inspections page (if this is your first time setting it), Pycharm already applies all the code rules to the current project.

Next, we will make two changes to the code checking mechanism:

(1) Mark spelling errors in green in the test script

(2) In the description document (comment), change the spelling error to red prompt

Next, we will introduce them one by one.

7. Create a scope

First we need to create two scopes for setting two different application scopes. Click the Settings button to go to the Settings/Preferences dialog box, open the Scopes page, click the green plus sign above to create a local type of scope:

In the Add New Scope dialog box, type the scope name, and then select the directory you want to include in the current scope in the Project Manager (tree structure): test_dir. Note that the load path is already automatically displayed in the Pattern column:

Repeat these steps to create a new Production scope.

8. Create a code inspection control file in the newly created scope

Next, create a copy of the default code control file (for security reasons):

Then name it, for example, MyProjectProfile. This new configuration file is a duplicate of the default configuration file, with exactly the same settings.

Next select the code control file we copied, navigate to Spelling and change accordingly. To quickly find the Spelling option leaf, simply type Spel in the search bar.

Then add the Test scope we created earlier by clicking the green plus sign, and then click Add Production scope again:

In the Test scope, the severity level of code inspection is shown on the left side of the figure, and in the Production scope, similar settings are available, but the security level in the drop-down list is different:

Note the font color of the scope name in the dialog box. If it is gray, it means that no changes have been made. If it is blue, it means that the relevant settings have been changed.

Apply the change settings and close the dialog box.

At this point, the configuration file modified as requested is complete and named MyProjectProfile, which has different spell checking settings in the Test and Production scopes. Next we apply this configuration to the corresponding code area, select Code→Inspect Code in the main program menu, and specify the defined scope and configuration file in the dialog box:

Of course we need to do this twice, because there are two domains that need to be configured and the associated configuration manifest can be exported.

Compare the spell-checking results for these two scopes:

As you can see, the red wavy line is in the Production scope and the green wavy line is in the Test scope.

9. Highlight code display of error prompt

Pycharm also highlights current errors based on profile controls.

For example, if your spellchecker configuration file contains the "Unresolved references" check rule and you use a symbol that has not been imported, Pycharm will underline the unexplained symbol to prompt you to import the relevant module:

Refer to auto-import tutorial to complete the import of related modules

10. Rapid prototyping and multiple prompts

Have you noticed how often a yellow or red light bulb lights up on the left side of your code and you don't want to see it?

11. Automatic generation of source code

Pycharm provides a lot of automatic code generation mechanism, you can refer to the product documentation on automatic code generation introduction: Auto-generating code, next we explore Pycharm's main code generation mechanism. Of course, we need to delete the existing content in Solver.py and start over.

First, create a class instance:

OK, Pycharm successfully created a class:

Next we add a member method to the class. To do this, we first need to type a dot after the class instance and then type the member function name. At this point the member function is undefined, so Pycharm prompts us to create one:

Then manually enter the source code in the function body. For example, we enter a program that calculates the discriminant of quadratic equations. There is a function sqrt () from the math module, but it is not included yet. We continue to enter and see how Pycharm solves this problem:

Therefore, our final source code is as follows:

However, the code lacks some important logical analysis. We need to analyze the discriminant result d. If it is zero or positive, we solve the roots of the equation normally; if it is negative, we need to throw an exception. How can Pycharm help us with this task?

Let's include a block of code with an if statement, i.e. check the statements that need to be executed when d is nonnegative:

Then press Ctrl+Alt+T, or click Code→Surround With in the main menu, Pycharm will pop up a drop-down menu showing the range control structures available in the current situation:

Select the if option and Pycharm automatically adds an if True: statement to the selected row:

We don't explain Boolean expressions too much here. If necessary, we simply replace True with d >= 0, then position the cursor to the last line, enter, the cursor will appear on the next line, keep the same indentation as if, type else: , and then observe Pycharm's pre-input prompt:

Enter again, move the cursor, and here we enter the code that throws the exception under Pycharm's powerful spelling prompt:

12. Code format modification

Looking at the Solver.py file again, you will see that there are many yellow marks in the scroll slot on the right. Hover the mouse over them and Pycharm will display the corresponding code formatting problems:

Fortunately, these messages are warning messages and will not affect the running results of the code, but the format problem is too much, so how to adjust the code format to be more beautiful and standardized?

This is code reformatting, so try it.

To invoke the formatting operation, simply press Ctrl+Alt+L or click Code→Reformat Code from the main menu, and we are surprised to find that all PEP8 formatting problems have been eliminated.

Of course, we can customize the formatting standard, open the code style settings dialog box, select the specified language (Python), and make the necessary changes:

13. Add comments to documents

After the code format is adjusted, there are still some yellow marks on the left side. After hovering, a warning message similar to "Missing docstring" will be prompted. The small yellow light bulb in front of the code will also prompt the same message:

The solution is also simple. Select Insert docstring from the drop-down menu that pops up. Pycharm will automatically add a formatted text as a comment document:

Note that there are several formats for comment documents. You can set the current format of comment documents to be inserted in Python Integrated Tools page, such as Epytext, plain text, etc.

14. Enter comments

Comment documentation is used to explain the parameters, return values, and types and meanings of variables. For example, if we need to control the input parameter type of demo(), we need to add the corresponding comment information in the comment document:

At this point, the comment documentation for the main function is complete.

Next, in the process of function call, if there is a mismatch of parameter types, Pycharm will give an error message in response according to the comment document:

At this point, I believe that everyone has a deeper understanding of "what is the application style of Pycharm code", so let's actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report