1

I want to print to a file using print I import from __future___. I have the following as an import:

from __future__ import print_function

From now on, I can print using:

print("stuff", file=my_handle)

However, I have many calls to print in a function, so I would want to be able to use a function where the keyword argument is bound to my_handle. So, I use partial application:

printfile = partial(print, file=my_handle)
printfile("stuff")
printfile("more stuff")

which is what I intended. However, is there any way I can change to definition of print itself by partially applying the keyword argument? What I have tried was:

print = partial(print, file=my_handle)

however I got an error saying:

UnboundLocalError: local variable 'print' referenced before assignment

Is there any way to use print without mentioning my file every time?

4

1 回答 1

0

print = partial(print, file=my_handle)

这一行在第二个上引起 UnboundLocalError,第二print个用作 的参数partial()。这是因为print在此特定函数中发现名称是局部变量 --- 因为您分配给它,在这种情况下在同一行中,更一般地在同一函数中。您不能在一个函数中使用相同的变量名有时引用全局变量,有时引用局部变量。

要修复它,您需要使用不同的名称:

fprint = partial(print, file=my_handle).

于 2013-04-14T13:27:56.537 回答