在Pycharm,Python,Django中将函数名称用作变量时出错:赋值前引用了局部变量'processed'

问题描述 投票:-1回答:2

我使用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
python django variables pycharm
2个回答
1
投票

一种简单的解决方案是:

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)

-1
投票

原因更有趣首先processed是功能参考,在这里您可以选择其他名称。是的,它应该为if request.method == "POST"大写,以匹配它未通过条件

但是有趣的是它应该已经返回了函数引用,但是这里的错误是UnboundError

尝试这段代码

def foo(bar): 
    return foo

print(foo(2)) #it will print function reference but not unbound

另一方面

def foo(bar): 
    if bar == 5:
       foo = 7
    return foo
print(foo(2)) #it will raise the `UnboundError` even if condition is never going to meet

原因是Abstract Syntax Tree定义函数时的python构建


-1
投票

原因更有趣首先processed是功能参考,在这里您可以选择其他名称。是的,它应该为if request.method == "POST"大写,以匹配它未通过条件

但是有趣的是它应该已经返回了函数引用,但是这里的错误是UnboundError

尝试这段代码

def foo(bar): 
    return foo

print(foo(2)) #it will print function reference but not unbound

另一方面

def foo(bar): 
    if bar == 5:
       foo = 7
    return foo
print(foo(2)) #it will raise the `UnboundError` even if condition is never going to meet

原因是Abstract Syntax Tree定义函数时的python构建

© www.soinside.com 2019 - 2024. All rights reserved.