For the most part, Python keeps you safe. You have to really try to shoot yourself in the foot. But here's one that's bitten me three times:

import numpy as np

def get_num(num=np.random.randint(1000)):
    print(num)

get_num()
get_num()

>> 612
>> 612
In Python3, keyword arguments can default to a function call. The Trick is, it looks like it only calls the function once. After that it uses the same default value every time.
If you need a fresh function call each time, you can use something like

def get_num(num=None):
if num is None:
num = np.random.randint(1000)
print(num)

get_num()
get_num()

>> 236
>> 960
You can follow @_brohrer_.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled: