首页 > 解决方案 > 在 Pycharm、Python、Django 中使用函数名作为变量时出错:分配前引用了局部变量“已处理”

问题描述

我使用 Pycharm Professional 2019.2、Python 3.7.4、Django 2.2.5。据我所知,函数名是模块中的全局变量。但我有一个否认这一点的功能。

def processed(request):
    if request.method == 'post':
        text = request.post['text']
        processed = text.upper()
    return HttpResponse(processed)

浏览器显示以下错误:

UnboundLocalError at /process/
local variable 'processed' referenced before assignment
Request Method: POST
Request URL:    http://127.0.0.1:8000/process/
Django Version: 2.2.5
Exception Type: UnboundLocalError
Exception Value:    
local variable 'processed' referenced before assignment

标签: pythondjangovariablespycharm

解决方案


一种简单的解决方案是:

def processed(request):
    # Do not use the function name as the parameter name.
    ret = processed

    # It should be 'POST', not 'post'.
    if request.method == 'POST':
        # It should be 'POST', not 'post'.
        text = request.POST['text']
        ret = text.upper()

    return HttpResponse(ret)

推荐阅读