In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail how to write python code that makes people look elegant and comfortable. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.
When many beginners start to learn a new language, they tend to ignore some details that should not be ignored, such as variable naming and function naming, as well as the standardization of annotations. In this regard, I specially collected some suitable for all the partners of learning Python, the way of clean code, so that the code you write makes people bright!
Write the Pythonic code
The first thing that comes to mind when it comes to specifications is Python's famous PEP8 code specification document, which defines best practices for writing Pythonic code. It can be found in the
Check it on https://www.python.org/dev/peps/pep-0008/. But there are not many friends who really study these specifications carefully. For this, this article selects some commonly used techniques and methods of clean code and standardization. Let's learn them together.
Naming
All programming languages have naming conventions for variables, functions, classes, and so on, and the beautiful Python certainly recommends using naming conventions. Then learn about classes, functions, methods, and so on.
Variables and functions
Use lowercase letters to name functions and variables, and use underscores to separate words to improve code readability.
Declaration of variables
Names = "Python" # variable name namejob_title = "Software Engineer" # variable name with underscore populated_countries_list = [] # variable name with underscore
You should also consider using non-Python built-in method names in your code, and use one or two underscores () if you use built-in method names in Python.
_ books = {} # variable name privatization _ _ dict = [] # prevent name confusion in the python built-in library
So how do you choose to use _ or _ _?
If you do not want the external class to access the variable, you should use an underscore (_) as the prefix for the internal variable of the class. Use (_ _) if the private variable name you want to define is a keyword such as dict in Python.
Declaration of function
Def get_data (): passdef calculate_tax_data (): pass
The declaration of a function, like a variable, is connected by lowercase letters and a single underscore.
Of course, for function privatization, it is also similar to declaring variables.
Def _ get_data (): pass
The function begins with a single underscore to privatize it. For functions that are named using keywords in Pyton
Use double underscores.
Def _ _ path (): pass
In addition to following these naming rules, it is important to use clear and understandable variable names.
Function name specification
# Wrong Waydef get_user_info (id): db = get_db_connection () user = execute_query_for_user (id) return user# Right waydef get_user_by (user_id): db = get_db_connection () user = execute_user_query (user_id) return user
Here, the second function, get_user_by, ensures that variables are passed with the same parameters, thus providing the correct context for the function. The first function, get_user_info, is not very clear, because what the parameter id means is not sure here, is it the user ID, the user payment ID or any other ID? This kind of code may cause confusion to other developers using your API. To solve this problem, I changed two things in the second function; I changed the name of the function and the name of the parameter passed, which made the code more readable.
As a developer, it is your responsibility to think carefully when naming variables and functions and to write code that is clear and easy to understand.
Of course, it is also convenient for yourself to maintain it in the future.
Naming conventions for classes
The name of the class should use hump case like most other languages.
Class UserInformation: def get_user (id): db = get_db_connection () user = execute_query_for_user (id) return user
Naming conventions for constants
You should usually define constant names in uppercase letters.
TOTAL = 56TIMOUT = 6MAX_OVERFLOW = 7
Parameters of functions and methods
The parameter naming of functions and methods should follow the same rules as variable and method names. Because the class method takes self as the first keyword argument. So don't use self as a keyword as an argument in a function to avoid confusion.
Def calculate_tax (amount, yearly_tax): passsclass Player: def get_total_score (self, player_name): pass
That's about all the emphasis on naming, let's take a look at the problems needed in expressions and statements.
Expressions and statements in code
Users = [{"first_name": "Helen", "age": 39}, {"first_name": "Buck", "age": 10}, {"first_name": "anni", "age": 9}] users = sorted (users, key=lambda user: user ["first_name"] .lower ())
What's wrong with this code?
At first glance, this code is not easy to understand, especially for new developers, because the syntax of lambdas is weird, so it is not easy to understand. Although using lambda here can save lines, this does not guarantee the correctness and readability of the code. At the same time, this code does not solve the problem that the dictionary lacks keys and has an exception.
Let's rewrite this code using a function to make it more readable and correct; this function will determine exceptions and is much easier to write.
Users = [{"first_name": "Helen", "age": 39}, {"first_name": "Buck", "age": 10}, {"name": "anni", "age": 9}] def get_user_name (users): "" Get name of the user in lower case "" return users ["first_name"] .lower (users): "" Sort the nested dictionary "" if not isinstance (users) Dict): raise ValueError ("Not a correct dictionary") if not len (users): raise ValueError ("Empty dictionary") users_by_name = sorted (users, key=get_user_name) return users_by_name
As you can see, this code checks for all possible unexpected values and is more readable than the previous single line of code. A single line of code looks cool and saves lines, but it adds a lot of complexity to the code. But that doesn't mean that a single line of code is not good. The point here is that if your single line of code makes the code harder to read, avoid using it and remember that code is not written to be cool, especially on the project team.
Let's consider another example where you try to read the CSV file and calculate the number of lines processed by the CSV file. The following code shows the importance of making code readable and how naming plays an important role in making code readable.
Import csvwith open ("employee.csv", mode= "r") as csv_file: csv_reader = csv.DictReader (csv_file) line_count = 0 for row in csv_reader: if line_count = 0: print (f'Column names are {"," .join (row)}') line_count + = 1 print (f'\ t {row ["name"]} salary: {row ["salary"]} 'f'and was born in {row ["birthday month"]}.) Line_count + = 1 print (f'Processed {line_count} lines.')
Breaking down code into functions helps make complex code easier to read and debug.
The code here performs multiple operations in the with statement. To improve readability, you can extract the code with process salary from the CSV file into another function to reduce the likelihood of errors.
Import csvwith open ("employee.csv", mode= "r") as csv_file: csv_reader = csv.DictReader (csv_file) line_count = 0 process_salary (csv_reader) def process_salary (csv_reader): "" Process salary of user from csv file. "" For row in csv_reader: if line_count = = 0: print (f'Column names are {"," .join (row)}') line_count + = 1 print (f'\ t {row ["name"]} salary: {row ["salary"]} 'f'and was born in {row ["birthday month"]}.) Line_count + = 1 print (f'Processed {line_count} lines.')
The code has become a lot easier to understand.
Here, you create a helper function instead of writing everything in a with statement. This gives the reader a clear understanding of the actual function of the function. If you want to handle a particular exception or want to read more data from the CSV file, you can further decompose the function to follow the principle of single responsibility, which is important to do one thing at a time.
The type of return statement is as consistent as possible.
If you want the function to return a value, make sure that all execution paths of the function return that value. However, if you expect the function to only perform the operation without returning a value, Python implicitly returns None as the default value for the function.
Let's take a look at a wrong demonstration:
Def calculate_interest (principle, time rate): if principle > 0: return (principle * time * rate) / 100def calculate_interest (principle, time rate): if principle
< 0: return return (principle * time * rate) / 100ChaPTER 1 PyThonIC ThInkIng 正确的示范应该是下面这样 def calculate_interest(principle, time rate): if principle >0: return (principle * time * rate) / 100else: return Nonedef calculate_interest (principle, time rate): if principle
< 0: return None return (principle * time * rate) / 100ChaPTER 1 PyThonIC ThInkIng 还是那句话写易读的代码,代码多写点没关系,可读性很重要。 使用 isinstance() 方法而不是 type() 进行比较 当比较两个对象类型时,请考虑使用 isinstance() 而不是 type,因为 isinstance() 判断一个对象是否为另一个对象的子类是 true。考虑这样一个场景:如果传递的数据结构是dict 的子类,比如 orderdict。type() 对于特定类型的数据结构将失败;然而,isinstance() 可以将其识别出它是 dict 的子类。 错误示范 user_ages = {"Larry": 35, "Jon": 89, "Imli": 12}type(user_ages) == dict: 正确选择 user_ages = {"Larry": 35, "Jon": 89, "Imli": 12}if isinstance(user_ages, dict): 比较布尔值 在Python中有多种方法可以比较布尔值。 错误示范 if is_empty = Falseif is_empty == False:if is_empty is False: 正确示范 is_empty = Falseif is_empty 使用文档字符串 Docstrings可以在 Python 中声明代码的功能的。通常在方法,类和模块的开头使用。 docstring是该对象的__doc__特殊属性。 Python 官方语言建议使用""三重双引号""来编写文档字符串。 你可以在 PEP8 官方文档中找到这些实践。 下面让我们简要介绍一下在 Python 代码中编写 docstrings 的一些最佳实践 。 方法中使用docstring def get_prime_number(): """Get list of prime numbers between 1 to 100."""" 关于docstring的格式的写法,目前存在多种风格,但是这几种风格都有一些统一的标准。 即使字符串符合一行,也会使用三重引号。当你想要扩展时,这种注释非常有用。 三重引号中的字符串前后不应有任何空行 使用句点(.)结束docstring中的语句 类似地,可以应用 Python 多行 docstring 规则来编写多行 docstring。在多行上编写文档字符串是用更具描述性的方式记录代码的一种方法。你可以利用 Python 多行文档字符串在 Python 代码中编写描述性文档字符串,而不是在每一行上编写注释。 多行的docstring def call_weather_api(url, location): """Get the weather of specific location. Calling weather api to check for weather by using weather api and location. Make sure you provide city name only, country and county names won't be accepted and will throw exception if not found the city name. :param url:URL of the api to get weather. :type url: str :param location:Location of the city to get the weather. :type location: str :return: Give the weather information of given location. :rtype: str""" 说一下上面代码的注意点 第一行是函数或类的简要描述 每一行语句的末尾有一个句号 文档字符串中的简要描述和摘要之间有一行空白 如果使用 Python3.6 可以使用类型注解对上面的docstring以及参数的声明进行修改。 def call_weather_api(url: str, location: str) ->Str: "Get the weather of specific location. Calling weather api to check for weather by using weather api and location. Make sure you provide city name only, country and county names won't be accepted and will throw exception if not found the city name."
If you use type annotations in Python code, you don't need to write parameter information.
For the specific usage of type annotations (type hint), please refer to the final guide for python type detection that I wrote earlier-- the use of Typing.
Module-level docstring
Generally, a module-level docstring is placed at the top of the file to briefly describe the use of the module.
These comments should be placed before the guide package, and the module documentation string should indicate the use and functionality of the module.
If you feel that the client needs to know the method or class explicitly before using the module, you can also briefly specify a specific method or class.
"" This module contains all of the network related requests. This module will check for all the exceptions while making the network calls and raise exceptions for any unknown exception.Make sure that when you use this module,you handle these exceptions in client code as:NetworkError exception for network calls.NetworkNotFound exception if network not found. "" import urllib3import json
When writing a document string for a module, you should consider doing the following:
Write a brief description of the current module
If you want to specify some modules that are useful to the reader, such as the code above, you can also add exception information, but be careful not to be too detailed.
NetworkError exception for network calls.NetworkNotFound exception if network not found.
Think of the module's docstring as a way to provide descriptive information about the module without discussing the specific operation methods of each function or class in detail.
Class-level docstring
The class docstring is mainly used to briefly describe the use of the class and its overall goal. Let's look at some examples to see how to write a class document string
Single-line class docstring
Class Student: "This class handle actions performed by a student." Def _ _ init__ (self): pass
This class has an one-line docstring, which briefly discusses the student class. As mentioned earlier, all the coding specifications for one line of docstring are followed.
Multiline class docstring
Class Student: "" Student class information. This class handle actions performed by a student. This class provides information about student full name, age, roll-number and other information. Usage: import student student = student.Student () student.get_name () > > 678998 "def _ init__ (self): pass
This class docstring is multiline; we've written a lot about the use of the Student class and how to use it.
Docstring of the function
The function document string can be written after the function or at the top of the function.
Def is_prime_number (number): "" Check for prime number. Check the given number is prime number or not by checking against all the numbers less the square root of given number.: param number:Given number to check for prime: type number: int: return: True if number is prime otherwise False.: rtype: boolean ""
If we use type annotations to further optimize it.
Def is_prime_number (number: int)-> bool: "" Check for prime number. Check the given number is prime number or not by checking against all the numbers less the square root of given number. ""
Conclusion
Of course, there are many specifications in Python. It is recommended that you optimize the code with reference to the Zen of Python and Pep8 to form a good habit of writing Pythonic code.
On how to write elegant and comfortable python code to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.