For the most part, Python keeps you safe. You have to really try to shoot yourself in the foot. But here& #39;s one that& #39;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
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
def get_num(num=None):
if num is None:
num = np.random.randint(1000)
print(num)
get_num()
get_num()
>> 236
>> 960