Python中return语句报错:非函数内使用及缩进异常问题
解决Python中return语句的缩进与函数范围错误
问题核心
return语句只能放在函数/方法的定义内部,你目前把return signup_result和return login_result直接写在了CognitoResponse类的方法外部,属于类级别的顶层代码,不符合Python语法规范,所以触发Pylance的"return can be used only within a function"提示。- 加缩进后仍报错,大概率是缩进层级混乱(比如混用空格和Tab、缩进量不统一,或者缩进后仍未进入函数代码块)。
具体修复步骤
把return语句移到对应函数内部
确保return语句缩进在def开头的方法定义块内,和函数内的其他业务代码对齐。正确的类结构示例:class CognitoResponse: def cognito_signup(self, username, password): # 你的注册逻辑代码 signup_result = {"code": 200, "msg": "注册成功"} return signup_result # 缩进在cognito_signup方法内部 def cognito_login(self, username, password): # 你的登录逻辑代码 login_result = {"code": 200, "msg": "登录成功", "token": "xxx"} return login_result # 缩进在cognito_login方法内部统一缩进格式
Python对缩进要求严格,禁止混用空格和制表符(Tab):- 把所有缩进替换为4个空格(Python官方推荐标准)
- 检查编辑器的缩进设置,确保默认用空格而非Tab
排查多余缩进
如果仍报"Unexpected indentation",检查以下内容:- 方法定义的
def行本身有没有多余缩进 return语句的缩进量是否和函数内其他代码(比如变量赋值、逻辑判断)完全一致
- 方法定义的
错误与正确代码对比
错误示例(return在函数外)
class CognitoResponse: def cognito_signup(self, username, password): signup_result = {"code": 200, "msg": "注册成功"} return signup_result # 此处处于类的顶层,不在函数内部,错误! def cognito_login(self, username, password): login_result = {"code": 200, "msg": "登录成功"} return login_result # 同样处于类的顶层,错误!
正确示例
class CognitoResponse: def cognito_signup(self, username, password): signup_result = {"code": 200, "msg": "注册成功"} return signup_result # 缩进在函数内部,符合语法 def cognito_login(self, username, password): login_result = {"code": 200, "msg": "登录成功"} return login_result # 缩进在函数内部,符合语法
内容的提问来源于stack exchange,提问作者anon
相关产品推荐
相关产品推荐

