Skip to content

Python - Best Practices, Tips, and Tricks

Tip
  • From collections use deque() for a better stack and queue implementation than list
  • From collections use namedtuple for a simple way to make meaningful tuples.
    • Note: Tuples are always sorted on the first element, both normal and named tuples.
  • Use math.inf or float('inf') to represent a valid 'infinite' value
  • Use math.floor(math.log10(x)) to get the magnitude and number of digits in x

Named Tuples

Use collections.namedtuple to create semantic tuples, instead of having to remember the placement of values using indices.

python
Pair = collections.namedtuple('Pair', ('a', 'b'))

pair = Pair(1, 'name1')
print("Output: ", pair.a, pair.b)

#> Output: 1 name1
Pair = collections.namedtuple('Pair', ('a', 'b'))

pair = Pair(1, 'name1')
print("Output: ", pair.a, pair.b)

#> Output: 1 name1

Constants

There is no const keyword in Python, to identify a variable as constant to other programmers (and yourself), best practice is to name it WITH_ALL_CAPS.

Interesting Tricks

Use a dictionary/hash table to encode lambda functions

python
lookup = {
	'a': lambda x, y: x+y
	'b': lambda x, y: x*y
}

for item in ['a', 'b']:
	if item in lookup
	result = lookup[item]
lookup = {
	'a': lambda x, y: x+y
	'b': lambda x, y: x*y
}

for item in ['a', 'b']:
	if item in lookup
	result = lookup[item]

Use a generator with yield to read in large files