996433618a49c61a1c1a3b80e0ebc2e808d854ad
Python/Improve Python Code Quality with Examples.md
| ... | ... | @@ -0,0 +1,247 @@ |
| 1 | +https://medium.com/pythons-gurus/clean-code-in-python-good-vs-bad-practices-examples-2df344bddacc |
|
| 2 | + |
|
| 3 | +# Improve Python Code Quality with Examples | Python’s Gurus |
|
| 4 | +Want to write better code? |
|
| 5 | +-------------------------- |
|
| 6 | + |
|
| 7 | +Clean Code in Python: Good vs. Bad Practices Examples |
|
| 8 | +----------------------------------------------------- |
|
| 9 | + |
|
| 10 | +Improve Python Code Quality with Clean Coding Practices! |
|
| 11 | +-------------------------------------------------------- |
|
| 12 | + |
|
| 13 | +[CyCoderX](https://medium.com/@cycoderx) |
|
| 14 | + |
|
| 15 | + |
|
| 16 | + |
|
| 17 | +[Python’s Gurus](https://medium.com/pythons-gurus) |
|
| 18 | + |
|
| 19 | +Photo by [Steinar Engeland](https://unsplash.com/@steinart?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com/?utm_source=medium&utm_medium=referral) |
|
| 20 | + |
|
| 21 | +As a [developer](https://medium.com/@casavoullis/a-day-in-the-life-of-a-data-engineer-what-to-expect-aae32b95b7e7) with over four years of experience, I have cultivated a deep passion for Python and its infinite capabilities. Python’s versatility and simplicity make it a go-to language for data engineering tasks, enabling developers to streamline complex processes with ease. |
|
| 22 | + |
|
| 23 | +Throughout my journey, I regularly share insights on [Python](https://python.plainenglish.io/mastering-python-list-comprehension-a-guide-to-cleaner-and-faster-code-5464c1283837) programming, from beginner tips to advanced techniques, helping others enhance their coding skills and stay abreast of the latest trends. |
|
| 24 | + |
|
| 25 | +In this guide, we’ll delve deeper into the concept of “Clean Code” in [Python](https://medium.com/pythoneers/beyond-print-statements-elevating-debugging-with-python-logging-715b2ae36cd5) by contrasting examples of good and bad practices. This comparison will illustrate how clean code principles can transform code from being hard to maintain and understand to being clear and efficient. |
|
| 26 | + |
|
| 27 | +> **Please consider** [**following me**](https://medium.com/@casavoullis) for more updates and insights; your support helps me continue creating valuable content |
|
| 28 | + |
|
| 29 | +Why Clean Code Matters |
|
| 30 | +---------------------- |
|
| 31 | + |
|
| 32 | +Writing clean code is essential for several reasons: |
|
| 33 | + |
|
| 34 | +* **Maintainability**: Clean code is easier to read, understand and maintain. |
|
| 35 | +* **Scalability**: Well-structured code can be scaled and extended more easily. |
|
| 36 | +* **Collaboration**: Clean code is more approachable for other developers, facilitating teamwork and code reviews. |
|
| 37 | +* **Debugging**: Errors and bugs are easier to spot and fix in clean code. |
|
| 38 | + |
|
| 39 | +> **Are you also interested in** [**SQL**](https://medium.com/@casavoullis/understanding-acid-compliance-in-databases-a-beginners-guide-45098ec8d0b4) **content? Click** [**here**](https://medium.com/@casavoullis/list/database-sql-sagas-by-charilaos-82d03d2209d0) **to check out my** [**list**](https://medium.com/@casavoullis/list/database-sql-sagas-by-charilaos-82d03d2209d0) **on** [**Medium**](https://medium.com/@casavoullis/list/database-sql-sagas-by-charilaos-82d03d2209d0). |
|
| 40 | + |
|
| 41 | +Examples of Bad Practices vs. Good Practices |
|
| 42 | +-------------------------------------------- |
|
| 43 | + |
|
| 44 | +Example 1: Variable and Function Names |
|
| 45 | +-------------------------------------- |
|
| 46 | + |
|
| 47 | +**Bad Practice:** |
|
| 48 | + |
|
| 49 | +``` |
|
| 50 | +def calc(a, b, c): |
|
| 51 | + return a + b - c |
|
| 52 | +``` |
|
| 53 | + |
|
| 54 | + |
|
| 55 | +In this example, the names of the variables and function are nondescriptive. It’s unclear what each variable represents or what the function does. |
|
| 56 | + |
|
| 57 | +**Good Practice:** |
|
| 58 | + |
|
| 59 | +``` |
|
| 60 | +def calculate_final_score(base_score, bonus_points, penalty): |
|
| 61 | + return base_score + bonus_points - penalty |
|
| 62 | +``` |
|
| 63 | + |
|
| 64 | + |
|
| 65 | +This code uses descriptive names, making it much clearer and more readable. |
|
| 66 | + |
|
| 67 | +Example 2: Single Responsibility Functions |
|
| 68 | +------------------------------------------ |
|
| 69 | + |
|
| 70 | +**Bad Practice:** |
|
| 71 | + |
|
| 72 | +``` |
|
| 73 | +def process_data(data): |
|
| 74 | + # Filter data |
|
| 75 | + data = [x for x in data if x > 0] |
|
| 76 | + # Calculate average |
|
| 77 | + average = sum(data) / len(data) |
|
| 78 | + # Print results |
|
| 79 | + print(f"Average: {average}") |
|
| 80 | + return data |
|
| 81 | +``` |
|
| 82 | + |
|
| 83 | + |
|
| 84 | +Here, `process_data` is doing too much: filtering data, calculating an average and printing results. |
|
| 85 | + |
|
| 86 | +**Good Practice:** |
|
| 87 | + |
|
| 88 | +``` |
|
| 89 | +def filter_positive_data(data): |
|
| 90 | + return [x for x in data if x > 0] |
|
| 91 | +def calculate_average(data): |
|
| 92 | + return sum(data) / len(data) |
|
| 93 | +def print_results(average): |
|
| 94 | + print(f"Average: {average}") |
|
| 95 | +data = filter_positive_data(raw_data) |
|
| 96 | +average = calculate_average(data) |
|
| 97 | +print_results(average) |
|
| 98 | +``` |
|
| 99 | + |
|
| 100 | + |
|
| 101 | +Dividing the functionality into three separate functions improves clarity and code reusability. |
|
| 102 | + |
|
| 103 | +Example 3: Error Handling |
|
| 104 | +------------------------- |
|
| 105 | + |
|
| 106 | +**Bad Practice:** |
|
| 107 | + |
|
| 108 | +``` |
|
| 109 | +def divide_numbers(x, y): |
|
| 110 | + return x / y |
|
| 111 | +``` |
|
| 112 | + |
|
| 113 | + |
|
| 114 | +This code does not handle the possibility of dividing by zero, which could lead to uncaught errors. |
|
| 115 | + |
|
| 116 | +**Good Practice:** |
|
| 117 | + |
|
| 118 | +``` |
|
| 119 | +def divide_numbers(x, y): |
|
| 120 | + if y == 0: |
|
| 121 | + raise ValueError("Cannot divide by zero.") |
|
| 122 | + return x / y |
|
| 123 | +``` |
|
| 124 | + |
|
| 125 | + |
|
| 126 | +Here, the code proactively handles the possibility of an error, avoiding potential problems. |
|
| 127 | + |
|
| 128 | +Example 4: Duplicated Code |
|
| 129 | +-------------------------- |
|
| 130 | + |
|
| 131 | +**Bad Practice:** |
|
| 132 | + |
|
| 133 | +``` |
|
| 134 | +def show_details(product): |
|
| 135 | + print(f"Name: {product['name']}") |
|
| 136 | + print(f"Price: {product['price']}") |
|
| 137 | + print(f"Category: {product['category']}") |
|
| 138 | +def show_summary(product): |
|
| 139 | + print(f"Name: {product['name']}") |
|
| 140 | + print(f"Price: {product['price']}") |
|
| 141 | +``` |
|
| 142 | + |
|
| 143 | + |
|
| 144 | +In this example, printing product details is duplicated in two functions. |
|
| 145 | + |
|
| 146 | +**Good Practice:** |
|
| 147 | + |
|
| 148 | +``` |
|
| 149 | +def print_product_info(product, details=False): |
|
| 150 | + print(f"Name: {product['name']}") |
|
| 151 | + print(f"Price: {product['price']}") |
|
| 152 | + if details: |
|
| 153 | + print(f"Category: {product['category']}") |
|
| 154 | +# Usage: |
|
| 155 | +print_product_info(product, details=True) |
|
| 156 | +print_product_info(product) |
|
| 157 | +``` |
|
| 158 | + |
|
| 159 | + |
|
| 160 | +The function `print_product_info` eliminates duplication and allows for greater flexibility. |
|
| 161 | + |
|
| 162 | +> _Your engagement, whether through claps, comments, or following me, fuels my passion for creating and sharing more informative content._**_If you’re interested in more_** [**_Python_**](https://medium.com/@casavoullis/configuring-like-a-pro-a-comprehensive-guide-to-pythons-configparser-26c49b898629) **_content, please consider following me. Alternatively, you can click_** [**_here_**](https://medium.com/@casavoullis/list/python-tips-by-charilaos-43b77ab29941) **_to check out my_** [**_Python list_**](https://medium.com/@casavoullis/list/python-tips-by-charilaos-43b77ab29941) **_on_** [**_Medium_**](https://medium.com/@casavoullis/list/python-tips-by-charilaos-43b77ab29941)**_._** |
|
| 163 | + |
|
| 164 | +Additional Tips for Writing Clean Code |
|
| 165 | +-------------------------------------- |
|
| 166 | + |
|
| 167 | +1\. Consistent Naming Conventions |
|
| 168 | +--------------------------------- |
|
| 169 | + |
|
| 170 | +Stick to a consistent naming convention throughout your code. This can be camelCase, snake\_case, or any other convention, but it should be uniform. |
|
| 171 | + |
|
| 172 | +2\. Use Comments Wisely |
|
| 173 | +----------------------- |
|
| 174 | + |
|
| 175 | +Comments should be used to explain why something is done, not what is done. The code itself should be self-explanatory if it follows clean coding principles. |
|
| 176 | + |
|
| 177 | +3\. Avoid Magic Numbers |
|
| 178 | +----------------------- |
|
| 179 | + |
|
| 180 | +Replace magic numbers with named constants to make your code more readable and maintainable. |
|
| 181 | + |
|
| 182 | +``` |
|
| 183 | +# Bad Practice |
|
| 184 | +area = length * 3.14 |
|
| 185 | +# Good Practice |
|
| 186 | +PI = 3.14 |
|
| 187 | +area = length * PI |
|
| 188 | +``` |
|
| 189 | + |
|
| 190 | + |
|
| 191 | +4\. Keep Functions Short |
|
| 192 | +------------------------ |
|
| 193 | + |
|
| 194 | +Each function should do one thing and do it well. If a function is getting too long, consider breaking it down into smaller functions. |
|
| 195 | + |
|
| 196 | +5\. Write Unit Tests |
|
| 197 | +-------------------- |
|
| 198 | + |
|
| 199 | +Unit tests help ensure your code works as expected and make it easier to spot and fix bugs. They also serve as documentation for your code. |
|
| 200 | + |
|
| 201 | +6\. Follow PEP 8 |
|
| 202 | +---------------- |
|
| 203 | + |
|
| 204 | +PEP 8 is the style guide for Python code. Following these guidelines helps keep your code consistent and readable. |
|
| 205 | + |
|
| 206 | +Photo by [Jen Theodore](https://unsplash.com/@jentheodore?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com/?utm_source=medium&utm_medium=referral) |
|
| 207 | + |
|
| 208 | +Conclusion |
|
| 209 | +---------- |
|
| 210 | + |
|
| 211 | +These examples show how “Clean Code” practices can significantly improve the clarity, efficiency and maintainability of Python code. Adopting these principles not only makes the code easier to work with for you and others but also teaches discipline and attention to detail, valuable skills for any programmer. |
|
| 212 | + |
|
| 213 | +By embracing clean code practices, you can write Python code that is not only functional but also elegant and easy to maintain. Whether you’re working on a solo project or collaborating with a team, clean code is the key to success. |
|
| 214 | + |
|
| 215 | +Final Words: |
|
| 216 | +------------ |
|
| 217 | + |
|
| 218 | +Thank you for taking the time to read my article. |
|
| 219 | + |
|
| 220 | +Hey There! I’m [Charilaos](https://medium.com/@casavoullis) [Alkiviades](https://www.linkedin.com/in/casavoullis/) Savoullis, a data engineer who loves crafting end-to-end solutions. I write articles about [Python](https://medium.com/@casavoullis/the-magic-of-lambda-%CE%BB-functions-b81aab917597), [SQL](https://medium.com/@casavoullis/postgresql-intro-a-powerful-open-source-database-system-0ae97ca3ab8a), [Databases](https://medium.com/@casavoullis/understanding-acid-compliance-in-databases-a-beginners-guide-45098ec8d0b4), [AI](https://medium.com/@casavoullis/openais-gpt-4o-model-unveiling-revolutionary-use-cases-a36b94b21d36), [Data Engineering](https://medium.com/@casavoullis/elevating-your-software-development-skills-in-2024-75e4845cbee7), [lifestyle](https://medium.com/@casavoullis/refactoring-your-routine-finding-joy-in-the-developers-daily-grind-257018236108) and [more](https://medium.com/@casavoullis/unleashing-the-power-of-distributed-computing-the-future-of-efficient-and-scalable-systems-5fb438f27d6e)! |
|
| 221 | + |
|
| 222 | +> For similar articles and updates, feel free to explore my Medium profile [https://medium.com/@casavoullis](https://medium.com/m/signin?actionUrl=%2F_%2Fapi%2Fusers%2Fac6b10350b4d%2Flazily-enable-writer-subscription&operation=register&redirect=https%3A%2F%2Fmedium.com%2F%40casavoullis&user=Charilaos+A+Savoullis&userId=ac6b10350b4d) |
|
| 223 | +> |
|
| 224 | +> **If you enjoyed this article, consider liking and following for future updates. |
|
| 225 | +> Join me as we explore the exciting world of** [**tech**](https://medium.com/@casavoullis/data-workflows-an-introduction-to-apache-airflow-9dc89d353c6e)**, data and beyond!** |
|
| 226 | +> |
|
| 227 | +> This article was first published on medium by Charilaos Savoullis. |
|
| 228 | + |
|
| 229 | +Don’t hesitate to connect with me on my socials: |
|
| 230 | +------------------------------------------------ |
|
| 231 | + |
|
| 232 | +L**inkedIn**: [https://bit.ly/3UK8KNk](https://bit.ly/3UK8KNk) |
|
| 233 | +**GitHub**: [https://bit.ly/3WrMzgm](https://github.com/asavoullis) |
|
| 234 | + |
|
| 235 | +**Interested in more** [**Python**](https://medium.com/@casavoullis/making-lists-sets-dictionaries-immutable-in-python-56126ba76a70) **content and** [**tips**](https://medium.com/@casavoullis/making-lists-sets-dictionaries-immutable-in-python-56126ba76a70)**? Click** [**here**](https://medium.com/@casavoullis/list/python-tips-by-charilaos-43b77ab29941) **to find out more!** |
|
| 236 | + |
|
| 237 | +**How about** [**Databases**](https://medium.com/@casavoullis/list/database-sql-sagas-by-charilaos-82d03d2209d0) **and** [**SQL**](https://medium.com/@casavoullis/list/database-sql-sagas-by-charilaos-82d03d2209d0) **content? Click** [**here**](https://medium.com/@casavoullis/list/database-sql-sagas-by-charilaos-82d03d2209d0) **to find out more!** |
|
| 238 | + |
|
| 239 | +Let me know in the comments below … or above, depending on your device [🙃](https://emojipedia.org/upside-down-face) |
|
| 240 | + |
|
| 241 | +_Thank you for being a part of the_ [**_Python’s Gurus community_**](https://medium.com/pythons-gurus)**_!_** |
|
| 242 | + |
|
| 243 | +_Before you go:_ |
|
| 244 | + |
|
| 245 | +* Be sure to **clap x50 time** and **follow** the writer ️👏**️️** |
|
| 246 | +* Follow us: [**Newsletter**](https://medium.com/pythons-gurus/newsletters/gurus-advisor) |
|
| 247 | +* Do you aspire to become a Guru too? **_Submit your best article or draft_** to reach our audience. |
|
| ... | ... | \ No newline at end of file |