如何让自动生成的代码返回类对象而非字符串元素的列表?
解决生成代码中返回类对象列表的问题
问题场景
编写脚本通过两个参数自动生成文件:
newName:类名前缀(比如SquadState中的Squad)- 追加字符串列表:比如
['.DOWN', '.UP']
期望生成的get_state_order函数返回类属性组成的列表(如[SquadState.DOWN, SquadState.UP]),但实际生成的是字符串列表['SquadState.DOWN', 'SquadState.UP']。修改时触发TypeError: 'str' object is not callable错误,相关代码及报错如下:
生成文件的代码片段:
file = f""" .... def get_state_order() -> list[{exercise_name.capitalize()}State]: \"\"\"Returns the order of the states of the exercise\"\"\" return {list(newName + abc for abc in states)} .... """
报错信息:
Traceback (most recent call last): File "/Users/work/PycharmProjects/KI/et_ki/models/exercises/automatisierung.py", line 91, in <module> create_exercise_file(exercise_name, states) File "/Users/work/PycharmProjects/KI/et_ki/models/exercises/automatisierung.py", line 67, in create_exercise_file return {list(exercise_name(newName + abc) for abc in states)} ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: 'str' object is not callable
错误原因
- 原代码中,
list(newName + abc for abc in states)会生成一个字符串列表,拼到生成的代码里后,return语句就变成返回字符串列表,而非类属性。 - 修改时误将字符串类型的
exercise_name当作函数调用(exercise_name(newName + abc)),导致触发"str对象不可调用"的错误。
解决方案
不需要在生成脚本中做类型转换,而是直接构建出正确的代码字符串,让生成的get_state_order函数直接返回类属性列表:
- 先拼接出每个类属性的字符串(比如
SquadState.DOWN),再用逗号连接成列表格式的字符串。 - 将这个字符串直接插入到生成的代码的
return语句中。
修改后的代码示例:
# 先构建类属性的字符串列表,再拼接成符合代码语法的格式 state_list_str = ', '.join(f"{newName}{abc}" for abc in states) file = f""" .... def get_state_order() -> list[{exercise_name.capitalize()}State]: \"\"\"Returns the order of the states of the exercise\"\"\" return [{state_list_str}] .... """
这样生成的代码中,return语句会是return [SquadState.DOWN, SquadState.UP],执行时自然返回类属性组成的列表,而非字符串列表。
内容的提问来源于stack exchange,提问作者Roni
相关产品推荐
相关产品推荐

