Most full Pycharm Tutorials (2)--code style

Source: Internet
Author: User
Tags change settings

1. Theme

This section of the tutorial mainly describes how to create a Python project and make it a pycharm code style. You will see Pycharm makes your source code become very concise and beautiful, with appropriate indentation, space and so on, so Pycharm is also a tool for quality management.

This tutorial does not explain how to program with Python, and more about Python programming: Python programming

2. Preparation work

Before you begin, confirm the situation:

(1) Installation of Pycharm2.7 or later version of the software

(2) A new Python project (File→new project) has been created, with reference to: Pycharm New project file

(3) has added two directories under the project: SRC and Test_dir (file→new or Alt+insert), details Reference: Pycharm New project file

(4) The corresponding Python file (file→new or Alt+insert) has been added to the engineering directory for details reference: Pycharm New project file

3, the code error highlighting mode

Opens a new Python file for editing (F4), which defaults to two lines of code: Author name and project name. The two lines of code appear because the Python file was created based on a file template, so the two variables are predefined.

Next enter the keyword class, and when you start typing, the pycharm's spelling prompt lists the candidates to help you complete the code:

(Refer to the Pycharm spelling tips for pycharm More information about the spelling tips)

This red wavy line marks the desired position for the next code entry, in which case it is a predefined identifier. Type the class name Solver, and the red wavy line will move to the class name. If you hover the mouse pointer over the wavy line, you will see the error message ("Colon expected"), and of course the red flag on the right scroll bar will give you the same error message.

OK, enter a colon and return. According to Python code style standards, you need to define the next class declaration, and of course we can cancel it by entering a space.

4, focus PEP8 code style check

However, these warning reminders are not visible by default, so the first thing to do is to elevate their priority to display. Click the Settings button, and then in the inspections page of the Settings/preferences dialog box, type PEP8 to find all the relevant options and select the Warning option in the corresponding Drop-down menu:

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

5, detailed PEP8 code style

Now that Ptcharm has been able to display its code specifications correctly, ensure the integrity of the code format you write. Next when we enter the Next statement (for example, Def demo (self,a,b,c):), Pycharm will report the current format problem according to the PEP8 code specification mechanism.

As you can see, Pycharm sets the PEP8 specification that it supports as the default normal Python code format standard. If you open the Inspections list, (ctrl+alt+s→inspections), you can see that pycharm loaded the pep8.py tool into your code to pinpoint your code style problem.

6, code check and related settings

By the way, if you look closely at the default settings for inspection profile on the Inspections page page (if you are setting it for the first time), Pycharm has already used all the code rules for the current project.

Next we make two changes to the code review Mechanism:

(1) Mark the spelling error as green in the test script

(2) in the explanatory document (note), change the spelling error to a red hint

And then we'll do a presentation.

7. Create a scope

First we need to create two scopes for two different scopes of application settings. Click the Settings button to enter the Settings/preferences dialog box, open the Scopes page, and click the green Gash above to create a local type scope:

In the Add New Scope dialog box, type the name of the role field, and then in the project Manager (tree structure), select the directory you want to include in the current scope: Test_dir, note that the pattern bar at this point has automatically displayed the load path:

Repeat these steps to create a new production scope.

8. Create a code check control file in a new scope

Next, create a copy file of the default code control file (in security consideration):

  

And then name it, for example we name it here as Myprojectprofile. This new configuration file is a copy of the default configuration file that was previously defaulted, and the settings are identical.

Next select our copy of the code control file, navigate to the spelling item to make the corresponding changes. To quickly find the spelling option leaf, simply enter Spel in the search field.

Then click the Green plus sign to add the new test scope that we created before, and then click Add Production scope again:

In the test scope, the strict level of code checking is shown on the left of the illustration, and there are similar settings in the production scope, but the security levels in the selected Drop-down list are different:

Note the name of the font color in the dialog box, if it is gray, the change is not made, if blue indicates that the relevant settings have been changed.

Apply the change settings and close the dialog box.

At this point, the modified profile is complete, named Myprojectprofile, and has a different spelling check setting in the test scope and production scope. Next, we apply this configuration to the corresponding code area, select Code→inspect code in the main program menu, and specify the scope and configuration file defined in the dialog box:

Of course we need to do this two times, because there are two defined domains that need to be configured for changes, and you can export the related configuration list.

Compare the results of the spelling checks for these two scopes:

As you can see, the production scope is a wavy red line, and the test scope is a green wavy line.

9, the error prompted the highlight code display

In addition, Pycharm will also highlight some of the current errors according to the profile control.

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

Refer to Auto-import Tutorial to complete the import of related modules

10. Rapid prototyping and multiple prompts

Have you noticed that in code left often appear a bright yellow or red light bulb and yet you don't want to see it.

11. Automatic generation of source code

Pycharm provides a lot of code generation mechanism, you can refer to the product documentation about the automatic generation of code Introduction: Auto-generating code, next we explore the pycharm of the main code generation mechanism. Of course, we need to first remove the content already in the solver.py and start over again.

First, create a class instance:

Ok,pycharm successfully created a class:

Next we add a member method to the class, and in order to do this we first need to enter a point number after the class instance, and then type the name of the member function. At this point, the member function is undefined, so pycharm prompts us to create a:

Then manually enter the source code in the body of the function, for example, we enter a two-time equation discriminant program, which has a function sqrt () from the math module, but is not yet included, we continue to enter, see how pycharm solve this problem:

Therefore, our source code in the end is as follows:

However, the code lacks some important logical analysis. We need to analyze the discriminant result D, if it is 0 or a positive number, then the root of the equation is normally solved; if it is negative, we need to throw an exception, and how Pycharm will help us to accomplish this task.

Let's use the IF statement to include a piece of code, that is, to select the statement that needs to be executed when D is non-negative:

Then press CTRL+ALT+T, or click the code→surround with option in the main menu, and Pycharm will pop up a drop-down menu showing the range control structure available in the current situation:

Select if option, Pycharm automatically adds if True: statement to selected row:

Here we do not explain too much about Boolean expressions, as needed we directly replace true with D >= 0, then position the cursor to the last line, enter, the cursor will appear on the next line, and if the same indentation, enter else:, and then observe pycharm given the input hint:

Enter again, move the cursor, here we type the code that throws the exception at the Pycharm strong spelling hint:

12, Code format modification

Looking at the solver.py file again, you'll see a lot of yellow marks in the right scroll slot, hover over the top, and pycharm will display the corresponding code formatting problem:

Fortunately, this information is a warning message, and will not affect the results of the operation of the code, but the format problem is too much, then how to adjust the code format more beautiful norms.

Here is the use of code reformatting, may wish to try.

To invoke a format operation, simply press the Ctrl+alt+l shortcut, or click Code→reformat Code in the main menu, and we are amazed to find that all the PEP8 class formatting problems have been eliminated.

Of course, we can customize the formatting criteria, open the Code Style Settings dialog box, select the specified language (Python), and make the necessary changes:

13, add the annotation document

After the code format is adjusted, the left side still leaves some yellow flag bit, the mouse hover prompts similar to "Missing docstring" warning message, the yellow light bulb in front of the code also prompts the same message:

The solution is also very simple, in the pop-up drop-down menu, select Insert DocString,Pycharm will automatically add a section of formatted text as a comment document:

Note that there are several formats for the annotation document, and you can set the annotation document that you want to insert in the Python integrated tools page, such as Epytext, plain text, etc.

14, input comments

The annotation document is used to interpret the function's arguments, return values, types of variables, and meanings. For example, we need to control the input parameter type of the demo (), we need to add the corresponding annotation information in the annotation document:

At this point, the annotation document for the main function is complete.

Next, in the process of a function call, if a parameter type mismatch occurs, Pycharm gives the response error message based on the annotation document:

For more information about Pycharm annotation documents see: Type hinting.



If you feel that this article has inspired you, please pay attention to my public number, I will be as active as possible to communicate with you, thank you.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.