In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what are the Python programming styles". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn what Python programming styles there are.
1.1 extra spaces
The following function assignments are customary:
Foo (a, bounty 0, {'afiuza 1), (10,))
However, none of the extra spaces shown below are customary:
# these spaces are all superfluous foo (a, b = 0, {'axiafiuu1,' bounded 2}, (10,))
The following code, with spaces, is more customary:
I + = 1 num = num**2 + 1 def foo (nums: List)
A space that is especially easy to ignore, there should be a space when adding function meta-information:
Def foo (nums: list): # according to the official recommendation here, nums: list should have a space pass.
1.2 whether it is judged by None or not
To determine whether an object is None, the following is customary:
If arr is None: pass if arr is not None: pass
The following writing is not in line with the habit and is generally rare:
If arr = = None: pass
In particular, for objects such as list,tuple,set,dict,str, use the following method to determine whether it is more customary to be None:
If if not arr: # is None, if pass if arr: # is not None, then pass is satisfied.
1.3 lamda expression
Lambda expressions are suitable for some key parameter assignments, etc., and are generally not used to writing:
F = lambda I: iTun1
The following is more customary:
Def is_odd (I): return iTunes 1
1.4 minimize protected code
To make the code more robust, we generally do defensive work, and it is more customary to minimize the protected code, as follows: add a try to ensure that the defense key is not a problem:
Try: val = d ['c'] except KeyError: print ('c' not existence)
The above is reasonable, but it is not customary for the following code to nest another function when capturing KeyError:
Try: val = foo (d [['c']) # this also catches the KeyError exception in the foo function except KeyError: print ('c 'not existence)
Writing like this also catches KeyError exceptions in the foo function, which is not customary.
1.5 maintain logical integrity
According to the official guide, only if logic return, while ignoring the possible else logic when x is negative, is not desirable:
Def foo (x): if x > = 0: return math.sqrt (x)
Suggest how to write it:
Def foo (x): if x > = 0: return math.sqrt (x) else: return None
Or write something like this:
Def foo (x): if x < 0: return None return math.sqrt (x)
Therefore, don't ignore usage habits in order to minimize the number of lines of code.
1.6 use a more semantically explicit approach
When determining whether a string ends with ize, it is not recommended to write:
If s [- 3:] = 'ize': print (' ends ize')
Using the endswith method of a string to determine whether it ends with a string is obviously more readable:
If s.endswith ('ize'): print (' ends ize')
As long as you pay more attention to the above, it is not a problem to understand. In fact, in addition to these coding habits specified by PEP8, there is also a programming style that is closely related to code robustness, which is highlighted today.
2 EAFP defense programming style
In order to improve the robustness of the code, we need to do defensive programming, and try and except in Python are mainly used to do this:
D = {'averse: 1,' baked: [1,2,3]} try: val = d ['c'] except KeyError: print ('key not existence')
The code in the try block is protected, and if the key does not exist, except catches the KeyError exception and handles the exception information.
And the following code, once the key does not exist from the dictionary, if there is no try protection, then the program is directly interrupted here, showing the phenomenon is app directly hang up or flash, which is obviously very unfriendly.
D = {'averse: 1,' baked: [1, 2, 3]} val = d ['c']
Another example used by try and except is to trigger an OSError exception if the directory already exists, catch it through except and do some exception handling logic in the block.
Import os try: os.makedirs (path) except OSError as exception: if exception.errno! = errno.EEXIST: raise # PermissionError and other exceptions else: # path directory already exists
The above defensive programming style using try and except has a more abstract name in Python: EAFP
Its full name is:
Easier to Ask for Forgiveness than Permission.
There is no need to dwell on the philosophical meaning of the above sentence.
Just know the meaning of the reference in programming: first believe that the program will execute correctly, and then if something goes wrong, we will deal with it.
Using the defensive style of try and except has obvious advantages. Only our business logic is written in try, exception handling logic is written in except, and there is almost no redundant code. This style is also advocated in the Python guide.
But everything has two sides, and this way of writing is no exception. So what's wrong with the EAFP defense style? It will mainly bring some side effects that we don't want to have.
For example, the logic in the try block is as follows: some situation occurs to modify a value in the disk's csv file, and the logic is completed successfully, but when you come to the following code, the program has an exception and is caught by except, and then do some exception handling:
Try: if condition: revise_csv # has contaminated the csv file do_something # triggered an exception except Exception: handle_exception
Because the logic in the try block is divided into two steps, they are not an atomic operation, so the csv file is modified first, but the do_something is abnormal, resulting in contamination of the csv file.
In fact, in addition to the above EAFP defensive programming style, there is another programming style that is completely different from it. Although it can solve the side effects of EAFP very well, its disadvantages are more obvious, so Python does not advocate a lot of use of this style.
3 LBYL defense programming style
Introduce another programming style: LBYL
Its characteristics: it means to check all kinds of possible errors before performing normal business logic, and it is necessary to write one if and else logic after another.
Such as EAFP-style code:
D = {'averse: 1,' baked: [1,2,3]} try: val = d ['c'] except KeyError: print ('key not existence')
Using LBYL to write is as follows:
If 'c' in d: val = d ['c'] else: print ('key not existence')
The EAFP-style code is as follows:
Import os try: os.makedirs (path) except OSError as exception: if exception.errno! = errno.EEXIST: raise # PermissionError and other exceptions else: # path directory already exists
Using LBYL to write is as follows:
Import os if not os.path.isdir (path): print ('not a legal path') else: if not os.path.exists (path): os.makedirs (path) else: print ('path already exists')
From the above two examples, you can see that the LBYL style is very different from the EAFP style.
LBYL has a lot of code if and else, and this style has the following disadvantages.
3.1 check every time the program runs
The program is checked every time it runs, regardless of whether the program actually triggers these exceptions.
If 'c'in d: # every required check val = d ['c'] if not os.path.isdir (path): # every necessary check print ('not a legal path') else: if not os.path.exists (path): # every required check os.makedirs (path) else: print ('path already exists')
3.2 it is difficult to consider all possible exceptions at once
It is difficult to consider all possible exceptions at once, and what is even more troubling is that once some exceptions are left out, the error is often not where it occurred, but in a very outer call. This will cause us to spend a lot of time debugging to find the ultimate error.
Def F1 if con1: # do1 if con2: # do2 # but omitted case 3 and did not report an exception in F1 function
3.3 decreased readability of the code
To write a lot of if-else that has nothing to do with the main logic, the real logic of the program becomes difficult to read. In the end, it is difficult for us to see whether this is just a judgment or a procedural logic / business judgment. However, if you use try-catch, you can write only the logic of the program in the try code block and handle all exceptions in except.
Thank you for your reading, the above is the content of "what Python programming style", after the study of this article, I believe you have a deeper understanding of what Python programming style is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.