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 are the bad habits of operation in Python

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

What are the bad habits of Python operation? in view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.

Many articles have introduced how to write a good Python, but today, on the contrary, I talk about a few bad habits when writing code. Some habits will make Bug hidden and difficult to track, of course, there are no mistakes, but personally feel that it is not perfect.

Note: the sample code is written in Python 3.6environment

1 use the list as the default parameter of the function

Look at the following example

Def func (a, b = []): b.append (a) print (fancia: {a}') print (fimb: {b}') func (1) func (2)

Normally, the result we expect should be like this.

A: 1 b: [1] a: 2 b: [2]

But when we execute the code, we only get this result.

A: 1 b: [1] a: 2 b: [1, 2]

Not as expected. Why? Because the Python list is a mutable object, and the function passing parameters are passed references, element 1 is already in b before the second call to the func method, and b finally has two elements 1 and 2 after the call.

In the example, the func method is relatively simple, and when you find a problem, you can find the root cause by simply looking at it. However, if you are in a more complex method, you may carelessly ignore this point and encounter some inexplicable problems.

So, when we want to set default parameters for a function, don't use mutable objects.

If the above code is changed to this, it will OK.

Def func (a, b = None): if b is None: B = [] b.append (a) print (fancia: {a}') print (fimb: {b}')

Get the expected results after implementation

A: 1 b: [1] a: 2 b: [2]

2 file operation

Many partners who just come into contact with Python can easily write similar code when doing file operations.

File = open ('file_name') try: for line in file: print (line) finally: file.close ()

This is no problem, but we do not need to maintain the file resources manually, just leave operations such as shutting down to the context manager.

With open ('file_name') as file: for line in file: print (line)

It doesn't look much refreshing.

3 catch all exceptions

Try: pass # do something except Exception as e: print (f'Exception {e}')

As above, sometimes it is easy to catch Exception exceptions in order to complete the function quickly. This may catch exceptions such as keyboard break (KeyboardInterrupt) (CTRL + C) or assertion error (AsstionError). Catching uncertain exceptions can sometimes cause inexplicable problems with our programs, and we should avoid doing so.

The accurate way is to catch specific exceptions such as ValueError, AttributeError, TypeError, etc. according to the context, and then do appropriate error handling, such as printing logs, and so on.

4 ignore the for of Python. Else syntax

In development, we can easily encounter similar requirements, in a list, to determine whether a particular element exists. For example, the following code determines whether an odd number exists in the list

Numbers = [1,2,3,4,5] is_odd_exist = False for n in numbers: if n% 2 = = 1: is_odd_exist = True break if is_odd_exist: print ('Odd exist') else: print (' Odd not exist')

Here, we use an identity is_odd_exist, which defaults to False. When an odd number is found, set it to True and jump out of the loop. It's okay to write this way, but we can do it another way.

Numbers = [1,2,3,4,5] for n in numbers: if n% 2 = = 1: print ('Odd exist') break else: print (' Odd not exist')

Let's first introduce the for of Python. Else syntax, when the for loop ends normally (that is, it does not end by jumping out of break), the statements in else are executed.

Here, we use a different way than other languages such as C, PHP, etc., to achieve the same function, it seems that the code is also a lot more concise.

5 use the key to traverse the dictionary

For beginners of Python, it may be easy to write such code.

Member = {'name':' xiaoming', 'age': 18,' mobile': '18312341234'} for key in member: print (f' {key}: {member [key]}')

Again, this is fine, but it doesn't look intuitive. When you traverse the dictionary, you can actually take out the key information directly, like this.

Member = {'name':' xiaoming', 'age': 18,' mobile': '18312341234'} for key, val in member.items (): print (f' {key}: {val}')

In that case, it seems to be clearer.

Some of the points mentioned above have their own certain prejudices and do not require everyone to accept them. Just choose a reasonable use.

The answers to the questions about the bad habits of Python are shared here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.

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