original builtins open def custom(*kargs**pargs)print('custom open call % :id kargspargsreturn original(*kargs**pargsbuiltins open custom to change open for every module in processthis code reassigns it in the built-in scope to custom version coded with nested defafter it saving the original in the enclosing scope so the customization can call it later this code is also partially previewas it relies on starred-argument forms to collect and later unpack arbitrary positional and keyword arguments meant for open-- topic coming up in the next much of the magic herethoughis nested scope closuresthe custom open found by the scope lookup rules retains the original for later usef open('script py'call built-in open in builtins read('import sys\nprint(sys path)\nx \nprint( * )\nfrom makeopen import makeopen makeopen('spam'import open resetter function custom open calls built-in open open('script py'call custom open in builtins custom open call 'spam'('script py',{ read('import sys\nprint(sys path)\nx \nprint( * )\nbecause each customization remembers the former built-in scope version in its own enclosing scopethey can even be nested naturally in ways that global variables cannot support--each call to the makeopen closure function remembers its own versions of id and originalso multiple customizations may be runmakeopen('eggs'nested customizers work toof open('script py'because each retains own state custom open call 'eggs'('script py',{custom open call 'spam'('script py',{ read('import sys\nprint(sys path)\nx \nprint( * )\nas isour function simply adds possibly nested call tracing to built-in functionbut the general technique may have other applications class-based equivalent to this may require more code because it would need to save the id and original values explicitly in object attributes--but requires more background knowledge than we yet haveso consider this part vi preview onlyimport builtins class makeopensee part vicall catches self(def __init__(selfid)self id id self original builtins open builtins open self def __call__(self*kargs**pargs)print('custom open call % :self idkargspargsreturn self original(*kargs**pargs scopes