python features you should know

I love python, it is bar none the quickest language to develop applications in. I've been a "pythonista" for around 7 years now, here are some features I think you shouldn't be sleeping on.

Underscores in large numbers

An easy win to start out with. It speaks for itself. Use underscores when working with large numbers in python your colleagues and future self will thank you.

without_underscores = 100000000
with_underscores = 100_000_000

collections.defaultdict
collection is my favourite and most used python module! It implements various container datatypes. collections.defaultdict allows you to initialise a default value to each key. To do so you are required to provide a function. Below I have used a lambda that takes in no arguments and always returns 0, to set a default value. You can also use built in functions such as list and dict to initialise the default value to another container. By using default dict we no longer need to check for the existence of a key and initiase the default value.

# here's some simple data processing
# let's count the number of occurences of ice cream flavour
data = ["chocolate", "chocolate", "strawberry", "matcha"]
count = {}

for elem in data:
if elem in count:
count[elem] += 1
else:
count[elem] = 1

print(count)
# using defaultdict instead
from collections import defaultdict
data = ["chocolate", "chocolate", "strawberry", "matcha"]
count = defaultdict(lambda: 0)

for elem in data:
count[elem] = 1

print(count)

collections.Counter

A bonus that is included within collections is collections.Counter. When passed an iterable this container will count the occurence of each element and return a dictionary of the element mapped to it's count. Essentially what we are doing above!

# using defaultdict instead
from collections import Counter
data = ["chocolate", "chocolate", "strawberry", "matcha"]
count = Counter(data)
print(count)

inspect

The inspect library lets you introspect live objects.
This can be super useful for debugging and also possibly for integration into test suites.


import inspect



def introspect(func):

print(inspect.signature(func))

def f(*args, **kwargs):
rv = f(**args, **kwargs)
return rv

return f


@introspect
def add(x: int, y: int = 10) -> int:
return x + y


add(5, 3)

# >>> (x: int, y: int = 10) -> int