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?

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
loudandclear
  • 2,306
  • 1
  • 17
  • 21

1 Answers1

0

print = partial(print, file=my_handle)

This line causes the UnboundLocalError on the second print, the one used as argument to partial(). This is because the name print is found to be a local variable in this particular function --- because you assign to it, in this case in the same line, more generally in the same function. You can't use the same variable name in one function to refer sometimes to a global and sometimes to a local.

To fix it you need to use a different name:

fprint = partial(print, file=my_handle).

Armin Rigo
  • 12,048
  • 37
  • 48