Python - Best Practices, Tips, and Tricks
Tip
- From
collectionsusedeque()for a better stack and queue implementation than list- From
collectionsusenamedtuplefor a simple way to make meaningful tuples.
- Note: Tuples are always sorted on the first element, both normal and named tuples.
- Use
math.inforfloat('inf')to represent a valid 'infinite' value- Use
math.floor(math.log10(x))to get the magnitude and number of digits inx
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 name1Pair = collections.namedtuple('Pair', ('a', 'b'))
pair = Pair(1, 'name1')
print("Output: ", pair.a, pair.b)
#> Output: 1 name1Constants
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