I'm a bit confused about a code in the book "Learning Python", p. 539.
As far as I know assignments within a function are only in this local scope. So if I want to change a global one I first have to declare it global
. But why does the following code change the builtin.open()
to custom
completely once called?
import builtins
def makeopen(id):
original = builtins.open
def custom(*pargs, **kargs):
print('Custom open call %r: ' % id, pargs, kargs)
return original(*pargs, **kargs)
builtins.open = custom
If I call makeopen('spam')
and a F = open('text.txt')
afterwards I get the custom
call. So the builtin.open()
has been changed in the whole script after the makeopen('spam')
. Why?
And if I would make some more makeopen('xx')
one builtin.open('text.txt')
would print the custom
call for every created makeopen
. Why?
Comparing this code to
x = 99
def changing():
x = 88
changing()
print(x)
doesnt even help me. Isn't it the same but with an x
instead of builtin.open()
?