nested scopes

Johann Hibschman johann at physics.berkeley.edu
Tue Feb 6 16:08:40 EST 2001


D-Man  writes:

> Do you know of any situations where it would be advantageous to have
> dynamic scoping instead of static scoping?  (Note that I'm not asking
> for situations where dynamic scoping exists, but where it would be
> better)

Well, it's very useful for output.  You can write all of your
functions to output to the standard output stream, and then redirect
that output stream with something like:

;;
;; Pseudo-lisp.  All of my function names are wrong, but I'm lazy.
;;
(let ((*standard-output-stream* (open-output-file "file.dat")))
  (generate-big-report))

That way, output will be redirected while you're inside
generate-big-report, but will automatically be switched back.
In python, a similar thing would be

try:
  temp = sys.stdout                   # redirect output.
  file = open('file.dat', 'w')
  sys.stdout = file
  generate_big_report()
finally:
  file.close()
  sys.stdout = temp                   # make sure that you fix it.

-- 
Johann Hibschman                           johann at physics.berkeley.edu




More information about the Python-list mailing list