Python函数默认值中的坑
文章目录
案例
代码段1
我们先来看framework中一段代码
def generate_utc(offset: int, now: float) -> datetime.datetime:
logging.info(f"System current time {now=}")
timestamp = now + offset
date_time_utc = datetime.datetime.utcfromtimestamp(timestamp)
logging.info(f"UTC date and time {date_time_utc=}")
return date_time_utc
def generate_time_utc(offset: int, now: float = time.time()):
date_time_utc = generate_utc(offset, now)
return date_time_utc.strftime("%H:%M:%S")
print(f"UTC time {generate_time_utc(offset=0)}")Output
2022-08-23 10:56:02,138 - UTC date and time date_time_utc=datetime.datetime(2022, 8, 23, 2, 56, 2, 138590)
UTC time 02:56:02这段代码片段是通过获取当前系统时间去计算出UTC的时间。从输出结果来看,这段代码按照预期正常工作了。但是当我们再次调用generate_time_utc会发生什么呢? 系统时间和计算出来的UTC时间是一致的吗?
开始实验,我对generate_time_utc 函数再进行多次调用,修改代码如下:
代码段2
print(f"UTC time {generate_time_utc(offset=0)}")
time.sleep(1)
print(f"UTC time {generate_time_utc(offset=0)}")
time.sleep(2)
print(f"UTC time {generate_time_utc(offset=0)}")
time.sleep(3)
print(f"UTC time {generate_time_utc(offset=0)}")
time.sleep(4)
print(f"UTC time {generate_time_utc(offset=0)}")Output
2022-08-23 11:11:11,568 - System current time now=1661224271.568321
2022-08-23 11:11:11,568 - UTC date and time date_time_utc=datetime.datetime(2022, 8, 23, 3, 11, 11, 568321)
UTC time 03:11:11
2022-08-23 11:11:12,570 - System current time now=1661224271.568321
2022-08-23 11:11:12,571 - UTC date and time date_time_utc=datetime.datetime(2022, 8, 23, 3, 11, 11, 568321)
UTC time 03:11:11
2022-08-23 11:11:14,573 - System current time now=1661224271.568321
2022-08-23 11:11:14,574 - UTC date and time date_time_utc=datetime.datetime(2022, 8, 23, 3, 11, 11, 568321)
UTC time 03:11:11
2022-08-23 11:11:17,586 - System current time now=1661224271.568321
2022-08-23 11:11:17,586 - UTC date and time date_time_utc=datetime.datetime(2022, 8, 23, 3, 11, 11, 568321)
UTC time 03:11:11
2022-08-23 11:11:21,589 - System current time now=1661224271.568321
2022-08-23 11:11:21,590 - UTC date and time date_time_utc=datetime.datetime(2022, 8, 23, 3, 11, 11, 568321)
UTC time 03:11:11我们可以看到输出结果,由Log 打出的系统时间一直在变,但是计算出的UTC时间却没有变。这个代码问题出现在哪里呢?
经过分析,我们发现问题出现在now的时间从一次到最后一次的值都是一样的,那为什么是一样的,按照我们常规的思维应该是不一样的才对。
如果对Python特性不熟悉的同学,从代码层面看似乎看不出任何问题。这时候就要翻阅Python官方文档了。
于是在函数的部分,看到以下的几句话,解决了我们的疑问。
Important warning: The default value is evaluated only once.
文档中很明确指出了,默认值只会计算一次。 所以不管我们调用函数多少次,缺省值始终都只会计算一次。
再回到framework 日志上去,从Framework log中,我们发现计算出UTC时间和系统时间前后间隔时间大约5~6分钟左右。
2022-08-19 11:27:13 [INFO] [system.py:synchronize_time:125] - Get offset=0
utc clock time 03:21:29如果按照前文我们的分析,应该在第一次调用的时候generate_time_utc 系统时间和计算出UTC时间肯定是会一致的,但是结果却没有。
代码段3
不妨我们做个实验来看一下。
首先创建一个my_method.py 实现三个函数
def func1():
print("Hi, I'm func1")
def run(func=func1()):
print(f"Hi, I'm run, {id(func)=}")
def demo():
pass接着,我们创建一个call_method.py, import my_method 中 demo 函数。
from my_method import demoRun call_method.py
Output
Hi, I'm func1我只调用了demo 输出显示我们对func1进行了调用,这个问题就出现在run(func=func1()) 我们在run 函数的默认参数中,进行了func1函数调用操作。
从这个实验,我们解释了为什么从Framework log中,我们发现计算出UTC时间和系统时间前后间隔时间大约5~6分钟左右 的问题。原因一定是在Job执行开始,调用了generate_time_utc 所在文件中其他方法或函数。导致time.time() 值已提前生成。
接着,我们看函数默认值其他注意点
不要使用可变对象作为默认值
def f(a, L=[]):
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))预期结果
[1]
[2]
[3]实际结果
[1]
[1, 2]
[1, 2, 3]为什么会出现这种问题,官方文档已给出解释。
“Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function
翻译如下:
在执行函数定义时,默认参数值是从左到右计算的。这意味着在定义函数时,表达式只计算一次,并且每次调用都使用相同的“预计算”值。当默认参数是可变对象(如列表或字典)时,理解这一点尤为重要:如果函数修改了对象(例如,通过将项附加到列表中),则默认值实际上被修改了。这通常不是预期的。解决此问题的方法是使用None作为默认值,并在函数体中显式测试它
修改代码之后,满足预期结果
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L总结
在函数中使用默认参数值时,需要注意以下几点:
- 请勿使用可变的对象(list, dictionary, or instances of most classes)作为默认参数值。
- 在使用默认参数值,需要注意默认参数值只会计算一次。如果需要变化的值,每次调用时都要向该参数传参。
END ~
看完了,点个赞呗 👇 (你的鼓励,是我更新的动力💪)!

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论