Skip to content

参数、权限、会话与错误适配:练习答案 ​

练习解答 ​

以下是完整离线文件,保存为answer.py后运行python answer.py;先建立与正文一致的初始状态,再验证变体。

python
def adapt(old):
    allowed={'prompt','cwd','sandbox'}
    if set(old)-allowed:raise ValueError('unsupported legacy field')
    if old.get('sandbox')!='read-only':raise PermissionError('only read-only migrated')
    if not old.get('cwd','').startswith('/'):raise ValueError('absolute cwd required')
    if not isinstance(old.get('prompt'),str) or not old['prompt'].strip():
        raise ValueError('prompt required')
    return {'thread_options':{'workingDirectory':old['cwd'],'sandboxMode':'read-only'},
            'input':old['prompt']}
new=adapt({'prompt':'read README','cwd':'/tmp/lab','sandbox':'read-only'})
assert new['thread_options']['sandboxMode']=='read-only'
try:adapt({'prompt':'read','cwd':'/tmp/lab','sandbox':'workspace-write'})
except PermissionError:pass
else:raise AssertionError('permission widened')
print('adapter preserves boundary')

for value in [
 {'prompt':'read','cwd':'/tmp/lab','sandbox':'read-only','network':True},
 {'prompt':'','cwd':'/tmp/lab','sandbox':'read-only'}]:
    try:adapt(value)
    except ValueError:pass
    else:raise AssertionError('invalid request accepted')
print('unsupported fields rejected')

忽略字段会使调用者以为某个限制已生效,实际执行却按下层默认值进行。

用心记录每一步成长