简体   繁体   English

导入信号时未绑定的局部变量错误?

[英]Unbound local variable error when importing signal?

I am importing signal at the beginning of my file. 我正在文件开头导入signal I then wish to use this in a function like so: 然后,我希望在这样的函数中使用它:

 os.kill(pid, signal.SIGKILL)

I get an error: 我收到一个错误:

UnboundLocalError: local variable 'signal' referenced before assignment.

If I instead import signal inside the function I get no such problem, why is this happening? 如果我改为在函数内import signal ,则不会出现此类问题,为什么会这样?

EDIT: example code 编辑:示例代码

import signal
def func():
    if args.kill: # Never triggered
        import signal
        os.kill(int(args.pid), signal.SIGKILL)
    elif args.name:
        os.kill(int(args.pid), signal.SIGKILL)

Importing a name in a function is also an assignment; 在函数中导入名称也是一种分配。 essentially your sample could be further reduced to this: 基本上,您的样本可以进一步简化为:

def function(arg1, arg2):
    if False:
        import signal

    os.kill(pid, signal.SIGKILL)

This makes signal a local variable in the function, and Python won't look for the global name. 这使signal成为函数中的局部变量,而Python不会寻找全局名称。

The import signal line makes signal a local name, but because the line is never executed, signal is never bound and the exception is thrown. import signal行使signal成为本地名称,但是由于从未执行该行,因此signal从未绑定,并且引发了异常。

Remove all import signal lines from the function, or move it out of the conditional to be imported unconditionally (and thus always bind signal ). 从函数中删除所有 import signal线,或将其从有条件移出以无条件导入(因此始终绑定signal )。

Your second 你的第二个

import signal

in the function is the problem. 在功能上就是问题所在。 Omit it. 不用了

It is just a local assignment as anything else: the module object will be assigned to the local name signal . 就像其他任何东西一样,它只是一个本地分配:模块对象将分配给本地名称signal

You can have it twice in a function - it is then local twice and the second import will do nothing, or you can it have once at the top of the function, but you cannot have it once buried deeply inside and only executed sometimes. 您可以在函数中使用它两次-然后在本地进行两次,第二次import将不执行任何操作,或者可以在函数顶部使用一次,但是不能一次将其深埋在内部并且只能执行一次。

In your case, the error will occur if not args.kill . 就您而言, if not args.kill ,则会发生错误。 Then the assignment will not happen, but the local name doesn't cease to exist. 这样就不会发生分配,但是本地名称不会不复存在。

Compare this to 比较一下

import signal as global_signal
signal = global_signal
def func():
    if args.kill: # Never triggered
        signal = global_signal
        os.kill(int(args.pid), signal.SIGKILL)
    elif args.name:
        os.kill(int(args.pid), signal.SIGKILL)
  • it is essentially the same, but with additional identifiers. 它本质上是相同的,但是带有附加的标识符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM