This article is part 2 of 100 BitSize Python Coding Tips and includes Tips 20 to 40.
21. Dictionary Comprehension with Conditional Logic
Use dictionary comprehensions with conditions to efficiently create dictionaries.
nums = [1, 2, 3, 4, 5]
num_to_square = {x: x**2 for x in nums if x % 2 == 0}
22. The any()
and all()
Functions
These functions are useful for checking conditions across iterables. any()
returns True
if any element of the iterable is true, while all()
returns True
if all elements are true.
conditions = [True, False, True]
print(any(conditions)) # True
print(all(conditions)) # False
23. getattr()
and setattr()
Dynamically access or set an attribute of an object.
class MyClass:
name = 'John'
obj = MyClass()
print(getattr(obj, 'name')) # 'John'
setattr(obj, 'name', 'Doe')
print(obj.name) # 'Doe'
24. The re
Module for Regular Expressions
Regular expressions are a powerful tool for string searching and manipulation.
import re
pattern = re.compile(r'\bfoo\b')
matches = pattern.findall('foo bar (foo) baz')
25. Using try
and except
Blocks
Exception handling is crucial for writing robust code.
try:
# risky operation
result = 10 / 0
except ZeroDivisionError:
print("Divided by zero!")
26. The glob
Module for File Paths
Use the glob
module to find files on the file system using patterns.
from glob import glob
for filename in glob('*.txt'):
print(filename)
27. The csv
Module for Reading and Writing CSV Files
Python’s built-in csv
module makes it easy to read and write CSV files.
import csv
with open('file.csv', mode='r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
28. The json
Module for JSON
Easily encode and decode JSON with the json
module.
import json
json_string = json.dumps([1, 'simple', 'list'])
print(json.loads(json_string))
29. Memory Management with gc
Understanding Python’s garbage collection (gc) can help in managing memory in larger applications.
import gc
gc.collect() # Explicitly trigger garbage collection
30. The functools
Module
functools
provides higher-order functions and operations on callable objects, such as partial
for partial function application and lru_cache
for memoization.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
31. Context Managers for Resource Management
Create your own context managers using the contextlib
module or by defining a class with __enter__
and __exit__
methods.
from contextlib import contextmanager
@contextmanager
def managed_resource(*args):
# Setup
resource = acquire_resource(*args)
try:
yield resource
finally:
# Cleanup
release_resource(resource)
32. Using slice
Objects for Readability
slice
objects can make your slicing operations more readable.
my_slice = slice(0, 5) # Equivalent to [0:5]
print(my_list[my_slice])
33. The operator
Module for Functional Programming
The operator
module provides function equivalents for arithmetic operations, comparison operations, and other fundamental Python operators, facilitating functional programming styles.
import operator
result = operator.add(1, 2) # Instead of 1 + 2
34. Using asyncio
for Asynchronous Programming
asyncio
provides a framework for writing single-threaded concurrent code using coroutines.
import asyncio
async def main():
print('Hello')
await asyncio.sleep(1)
print('world!')
asyncio.run(main())
35. Advanced String Formatting
Leverage Python’s advanced string formatting features for more control over text representation.
name = "John"
formatted = f"Hello, {name.upper()}!"
print(formatted)
36. The decimal
Module for Precise Arithmetic
Use the decimal
module for more accurate decimal arithmetic, useful in financial applications.
from decimal import Decimal
result = Decimal('0.1') + Decimal('0.2')
print(result) # '0.3', not 0.30000000000000004
37. The unittest
Framework for Testing
The unittest
module provides a way to test your Python code, ensuring it works as expected.
import unittest
class TestSum(unittest.TestCase):
def test_sum(self):
self.assertEqual(sum([1, 2, 3]), 6, "Should be 6")
if __name__ == '__main__':
unittest.main()
38. The datetime
Module for Working with Dates and Times
Handling date and time is made easy with the datetime
module.
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
39. Using Type Hints
Type hints help in making your code more readable and allowing for better static analysis.
def greet(name: str) -> str:
return f"Hello, {name}"
40. Exploiting Python’s Dynamic Nature
Python’s dynamic nature allows for metaprogramming and dynamic attribute access, which can be powerful in the right hands.
class MyClass:
pass
obj = MyClass()
obj.new_attribute = "Dynamic value"
print(obj.new_attribute)