Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Harsh Patel
Harsh Patel

Posted on

     

Better Coding Practices / Python / Part-1

Introduction

Code review is an integral part of a developer's day-to-day life. Getting mega pint of code review comments has lots of problems but most importantly it hurts developer-ego! I hope you'll find this article helpful.

Disclaimer: This blog does not claim to be one-and-only solution for all coding problems. Apart from some adopted community guidelines everything is subjective to the coder or reviewer. This is merely my opinions and compiled list of bad coding practices I've found through my experience. All the code examples are made to demonstrate a single problem at a time.

1. Variable Names

Bad

temp={"banana":"yellow","apple":"red","grape":"green"}list1=[]list2=[]fork,vintemp.items():list1.append(k)list2.append(v)print(f"fruits:{list1}")print(f"colors:{list2}")
Enter fullscreen modeExit fullscreen mode

Good

fruit_colors={"banana":"yellow","apple":"red","grape":"green"}fruits=[]colors=[]forfruit,colorinfruit_colors.items():fruits.append(fruit)colors.append(color)print(f"fruits:{fruits}")print(f"colors:{colors}")
Enter fullscreen modeExit fullscreen mode

Pros

  • Code readability
  • Less-prone to bugs

2. Exeption Handling

Bad

try:fruit_colors={"banana":"yellow","apple":"red","grape":"green"}color=fruit_colors["watermelon"]exceptException:print("Failed to get color of watermelon :(")
Enter fullscreen modeExit fullscreen mode

Good

fruit_colors={"banana":"yellow","apple":"red","grape":"green"}try:color=fruit_colors["watermelon"]exceptKeyError:print("Failed to get color of watermelon :(")
Enter fullscreen modeExit fullscreen mode

Pros

  • Code readability
  • Easy troubleshooting

3. Utilizing Standard Library

Bad

fruits=["apple","banana","grape"]i=0forfruitinfruits:print(f"{i}:{fruit}")i+=1
Enter fullscreen modeExit fullscreen mode

Good

fruits=["apple","banana","grape"]fori,fruitinenumerate(fruits):print(f"{i}:{fruit}")
Enter fullscreen modeExit fullscreen mode

Pros

  • Compact

4. Error Logging

Bad

try:res=requests.get("https://www.google.com")res.raise_for_status()logging.info("Success!")exceptExceptionase:logging.error(f"Unexpected error occured:{e}")
Enter fullscreen modeExit fullscreen mode

Good

try:res=requests.get("https://www.google.com")res.raise_for_status()logging.info("Success!")exceptHTTPErroraserr:logging.error(f"Request failed with status code:{err.response.status_code}")exceptException:# logging.exception logs traceback informationlogging.exception("Unexpected error occured:")
Enter fullscreen modeExit fullscreen mode

Pros

  • Code readability
  • Easy troubleshooting

5. Block Comments

Bad

username=username.lower()username=username.strip()username=re.sub(r"\s+","",username)ifnotre.match(r"^[a-zA-Z0-9_]{5,20}$",username):print("Invalid username")exit(1)
Enter fullscreen modeExit fullscreen mode

Good

# Perform string transforms on the usernameusername=username.lower()username=username.strip()username=re.sub(r"\s+","",username)# Check if username is validifnotre.match(r"^[a-zA-Z0-9_]{5,20}$",username):print("Invalid username")exit(1)
Enter fullscreen modeExit fullscreen mode

Pros

  • Code readability

Conclusion

This blog is a part of a series and each of these points can be extended with some advanced scenarios. Unfortunately, I can't mention all the scenarios in a single blog so I will try to cover other cases in future parts. Feel free to reach out if you have any questions, suggestions for improvments or any good coding practice you've found.

See post on my blog:https://alacrity.dev/better-coding-practices-python-part-1/

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Python ❤️ | Open Source & Machine Learning Enthusiast 🐣
  • Location
    Gujarat, India
  • Work
    Software Engineer at Crest Data Systems
  • Joined

Trending onDEV CommunityHot

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp