Sitemap
Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

10 Ways to Write Better Python Codes

11 min readJul 26, 2024

--

Python Block — (Image by Author)
(Image by Author)

Why Python?

How to write better Python codes?

1. Using “Generators” to Save Memory

def process_large_file(file_path):
"""
Generator function to read a large file line by line.
"""
with open(file_path, 'r') as file:
for line in file:
yield line

# Specify the path to your large file
log_file_path = 'path/to/your/large_file.txt'

# Use the generator to process the large file line by line
for line in process_large_file(log_file_path):
print(line.strip()) # .strip() removes any extra whitespace or newline characters

2. Using “.setdefault()” in Dictionaries

# Initial inventory
inventory: dict[str, int] = {"jeans": 500, "top": 600}

# Add more products with default stock levels if they are not already present
products_to_add: list[str] = ["skirt", "shirt", "tee"]

for product in products_to_add:
inventory.setdefault(product, 500)

# Print the final updated inventory
print("Final updated inventory:", inventory)

"""
# Output:
Final updated inventory: {'jeans': 500, 'top': 600, 'skirt': 500, 'shirt': 500, 'tee': 500}
"""

3. Using Dictionaries to avoid “if-elif” hell

from collections.abc import Callable

# Function 1
def first():
print("Calling First Function...")


# Function 2
def second():
print("Calling Second Function...")


# Function 3
def third():
print("Calling Third Function...")


# Function Default
def default():
print("Calling Default Function...")

# User Input
options: int = int(input("Enter an option :", ))

# Dictionary to hold options as key and functions as values
funcs_dict : dict[int, Callable[[], None]] = {1: first, 2: second, 3: third}

# Checking if the key exist and incase it doesn't then deafult function will run
final_result = funcs_dict.get(options, default)
final_result()
"""
# Output:
# When Option send was 0
Enter an option :0
Calling Default Function...

# When Option send was 1
Enter an option :1
Calling First Function...

# and so on...
"""

4. Using “Counter” from Collections Module

from collections import Counter
import re

# Read the text file
with open("sample_text.txt", "r") as file:
text = file.read()

# Clean and Tokenize the text
cleaned_text: str = re.sub(r'[^\w\s]', '', text.lower().split())

# Use Counter() to count the words
word_counts: Counter = Counter(cleaned_text)

# Printing second highest most common word
most_commmon = counter.most_common(2) # passed in Number will denotes how many common numbers we want (counting starts from 1-n)
print("Second Most Common Word is: ", most_commmon[0]) # print in zeroth index element from 2 most common ones

"""
# Output:
Second Most Common Number is: ('data', 82)
"""

5. Using “Memoization” to Optimize Code

import time

def memo_fibonacci(num: int, dictionary: dict[int, int]):
if num in dictionary:
return dictionary[num]
else:
dictionary[num] = memo_fibonacci(num-1, dictionary) + memo_fibonacci(num-2, dictionary)
return dictionary[num]

# Catching using a Dictionary
dictionary: dict[int, int] = {0: 1, 1: 1}

# Elapsed time
start_time: float = time.time()
# Calling the function
result: int = memo_fibonacci(48, dictionary)
end_time: float = time.time()
# Calculating the elapsed time
elapsed_time: float = end_time - start_time


print(f"Result: {result}") # Result: 7778742049
print(f"Elapsed time: {elapsed_time:.6f} seconds") # Elapsed time: 0.000133 seconds

6. Using “@decorators” to avoid Repetitiveness

import time

def elapsed_time(func):
def wrapper():
start_time: float = time.time()

func()

end_time: float = time.time() - start_time
print(f"{func.__name__}() took {end_time:.6f} seconds")

return wrapper

@elapsed_time
def some_code():
# Simulating running code..
time.sleep(0.00002)

# Calling the function
some_code() # some_code() took 0.000009 seconds

7. Using `dataclass` for Clean Data Structures

(Image by Author)
from dataclasses import dataclass

@dataclass
class Employee:
id_: int
name: str
salary: float

e1 = Employee(id_=1, name='Tusk', salary=69999.99)
print(e1) # Employees(id_=1, name='Tusk', salary=69999.99)
from dataclasses import dataclass

@dataclass
class Employee:
id_: int
name: str
salary: float

def __repr__(self):
return f"Employee(id_={self.id_}, name={self.name}, salary={self.salary})"

def __str__(self):
return f"{self.name} earns ${self.salary}."

e1 = Employee(id_=1, name='Tusk', salary=69999.99)
print(repr(e1)) # Employee(id_=1, name=Tusk, salary=69999.99)
print(str(e1)) # Tusk earns $69999.99.

8. Using “match” for Clean Input Handling

from dataclasses import dataclass

# Defining a class using dataclass
@dataclass
class Point:
x: int
y: int

# Match statements to handle different cases
def where_is(point):
match point:
case Point(x=0, y=0):
return ("Origin")
case Point(x=0, y=y):
return (f"Y={y}")
case Point(x=x, y=0):
return (f"X={x}")
case Point(x, y):
return("Somewhere else")
# To catch anything else that the user inputs
case _:
return("Not a point")

# Examples
print(where_is(Point(0, 0))) # Output: Origin
print(where_is(Point(0, 10))) # Output: Y=10
print(where_is(Point(10, 0))) # Output: X=10
print(where_is(Point(10, 10))) # Output: Somewhere else
print(where_is("Not a point")) # Output: Not a point

9(A). Using “all” Operator instead “and”

# User input from a registration form 
form_data: dict[str, str] = {"name" : "Nikita",
"email": "analyticalnikita@gmail.com",
"phone": "123478911"}

# List of reuired fields
required_fields: list[str] = ["name", "email", "phone"]

# Using all operator
if all(field in form_data for field in required_fields):
print("All required fields are filled out.")
else:
print("Some required fields are missing or empty.")

"""
# Output:
All required fields are filled out.
"""

9(B). Using “any” Operator instead “or”

# List of permissions to the user
user_permission: list[str] = ["read", "execute"]

# Check if user has at least one of the required permissions
required_permissions: list[str] = ["write", "read", "admin"]

# Using "all" operator
if any(permission in user_permission for permission in required_permissions):
print(f"Since you have required permissions. Access is allowed.")
else:
print("You're a standard user. Not allowed the access.")

"""
# Output:
Since you have required permissions. Access is allowed.
"""

10. Using the Comprehensions for Shorter Syntax

10(A). List Comprehensions

# Nested-if using List Comprehension
fruits: list[str] = ["apple", "orange", "avacado", "kiwi", "banana"]
basket: list[str] = ["apple", "avacado", "apricot", "kiwi"]

[i for i in fruits if i in basket if i.startswith("a")] # ['apple', 'avacado']

10(B). Tuple Comprehensions

# Generator expression converted to a tuple
tuple(i**2 for i in range(10))

# (0, 1, 4, 9, 16, 25, 36, 49, 64, 81)

10(C). Dictionary Comprehensions

# Creating a list of apple names
apple_names: list[str] = ["apple", "pineapple", "green apple"]

# Creating a dictionary with apple names as keys and their lengths as values
print({apple_name: len(apple_name) for apple_name in apple_names})

# {"apple": 5, "pineapple": 9, "green apple": 11}

10(D). Set Comprehensions

# Creating a set with condition
print({i**2 for i in range(1, 11) if i > 5})

# {64, 36, 100, 49, 81}

Conclusion

--

--

Level Up Coding
Level Up Coding
Nikita Prasad
Nikita Prasad

Written by Nikita Prasad

💻 Documenting my Learning in Simplified ways. 🚀 Join my data-driven journey, today! https://nikita-prasad-analyst.my.canva.site/lets-connect

Responses (30)