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 that need to be abandoned in Python development

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

Share

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

What are the bad habits that need to be abandoned in Python development? most people do not understand the knowledge points of this article, so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "what bad habits need to be abandoned in Python development" article.

1. Use the + sign for stitching strings.

Bad practice:

Def manual_str_formatting (name, subscribers): if subscribers > 100000: print ("Wow" + name + "! you have" + str (subscribers) + "subscribers!") Else: print ("Lol" + name + "that's not many subs")

It is a good practice to use f-string, and it will be more efficient:

Def manual_str_formatting (name, subscribers): # better if subscribers > 100000: print (f "Wow {name}! you have {subscribers} subscribers!") Else: print (f "Lol {name} that's not many subs") 2, use finaly instead of context manager

Bad practice:

Def finally_instead_of_context_manager (host, port): s = socket.socket (socket.AF_INET, socket.SOCK_STREAM) try: s.connect ((host, port)) s.sendall (b'Hello, world') finally: s.close ()

It is a good practice to use the context manager to close socket:: even if an exception occurs

Def finally_instead_of_context_manager (host, port): # close even if exception with socket.socket (socket.AF_INET, socket.SOCK_STREAM) as s: s.connect ((host, port)) s.sendall (b'Hello, world') 3. Try to close the file manually

Bad practice:

Def manually_calling_close_on_a_file (filename): F = open (filename, "w") f.write ("hello!\ n") f.close ()

It is a good practice to use the context manager. Even if an exception occurs, the file will be closed automatically. If you have a context manager, you should first use:

Def manually_calling_close_on_a_file (filename): with open (filename) as f: f.write ("hello!\ n") # close automatic, nothing is written after even if exception4 and except

Bad practice:

Def bare_except (): while True: try: s = input ("Input a number:") x = int (s) break except: # oops! Can't CTRL-C to exit print ("Not a number, try again")

This will catch all exceptions, resulting in pressing the CTRL-C program will not be terminated, it is a good practice

Def bare_except (): while True: try: s = input ("Input a number:") x = int (s) break except Exception: # better than this is to use ValueError print ("Not a number, try again") 5, function parameters to use variable objects

If the function argument uses a mutable object, then the next call may produce unexpected results, bad practice

Def mutable_default_arguments (): def append (n, l = []): l.append (n) return l L1 = append (0) # [0] L2 = append (1) # [0,1]

Good practice:

Def mutable_default_arguments (): def append (n, l=None): if l is None: l = [] l.append (n) return l L1 = append (0) # [0] L2 = append (1) # [1] 6, never use deduction

A bad practice

Squares = {} for i in range (10): squares [I] = I * I

Good practice.

Odd_squares = {I: I * i for i in range (10)} 7, addictive for guided use

Although the deductive type is easy to use, it should not be done at the expense of readability.

C = [sum (a [n * I + k] * b [n * k + j] for k in range (n)) for i in range (n) for j in range (n)]

Good practice:

C = [] for i in range (n): for j in range (n): ij_entry = sum (a [n * I + k] * b [n * k + j] for k in range (n)) c.append (ij_entry) 8, check type consistency = =

A bad practice

Def checking_type_equality (): Point = namedtuple ('Point', [' x','y']) p = Point (1,2) if type (p) = tuple: print ("it's a tuple") else: print ("it's not a tuple")

Good practice.

Def checking_type_equality (): Point = namedtuple ('Point', [' x','y']) p = Point (1,2) # probably meant to check if isinstance of tuple if isinstance (p, tuple): print ("it's a tuple") else: print ("it's not a tuple") 9, use = = to determine whether it is a single case

A bad practice

Def equality_for_singletons (x): if x = = None: pass if x = = True: pass if x = = False: pass

Good practice.

Def equality_for_singletons (x): # better if x is None: pass if x is True: pass if x is False: pass10, judge a variable with bool (x)

A bad practice

Def checking_bool_or_len (x): if bool (x): pass if len (x)! = 0: pass

Good practice.

Def checking_bool_or_len (x): # usually equivalent to if x: pass11, using a C-like for loop

A bad practice

Def range_len_pattern (): a = [1,2,3] for i in range (len (a)): v = a [I]. B = [4,5,6] for i in range (len (b)): av = a [I] bv = b [I].

Good practice.

Def range_len_pattern (): a = [1,2,3] # instead for v in a:... # or if you wanted the index for i, v in enumerate (a):... # instead use zip for av, bv in zip (a, b): .12, impractical dict.items

A bad practice

Def not_using_dict_items (): d = {"a": 1, "b": 2, "c": 3} for key in d: val = d [key].

Good practice.

Def not_using_dict_items (): d = {"a": 1, "b": 2, "c": 3} for key, val in d.items (): .13. Unpack tuple using index

A bad practice

Mytuple = 1,2x = mytuple [0] y = mytuple [1]

Good practice.

Mytuple = 1,2x, y = mytuple14, time spent using time.time () statistics

A bad practice

Def timing_with_time (): start = time.time () time.sleep (1) end = time.time () print (end-start)

It's a good idea to use time.perf_counter (), which is more precise:

Def timing_with_time (): # more accurate start = time.perf_counter () time.sleep (1) end = time.perf_counter () print (end-start) 15, logging uses print instead of logging

A bad practice

Def print_vs_logging (): print ("debug info") print ("just some info") print ("bad error")

Good practice.

Def print_vs_logging (): # versus # in main level= logging.DEBUG fmt ='[% (levelname) s]% (asctime) s -% (message) s' logging.basicConfig (level=level, format=fmt) # wherever logging.debug ("debug info") logging.info ("just some info") logging.error ("uh oh: (") 16. Use shell=True when invoking external commands

A bad practice

Subprocess.run (["ls-l"], capture_output=True, shell=True)

If shell=True, passing ls-l to the ls program on / bin/sh (shell) instead of Unix causes subprocess to produce an intermediate shell process; in other words, using intermediate shell means that variables in the command string, glob mode, and other special shell functions are preprocessed before the command runs. For example, $HOME is processed before the echo command is executed.

It is a good practice to refuse to execute from shell:

Subprocess.run (["ls", "- l"], capture_output=True) 17. Never try to use numpy

A bad practice

Def not_using_numpy_pandas (): X = list (range (100)) y = list (range (100)) s = [a + b for a, b in zip (x, y)]

Good practice:

Import numpy as npdef not_using_numpy_pandas (): # faster performance x = np.arange (100y) y = np.arange (100s) s = x + y18, like import *

A bad practice

From itertools import * count ()

In that case, no one has until the script has most variables. It's a good practice:

From mypackage.nearby_module import awesome_functiondef main (): awesome_function () if _ _ name__ ='_ _ main__': main () the above is about "what are the bad habits that need to be abandoned in Python development?" I believe you all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

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