UnboundLocalError: Local variable 'Tee' referenced before assignment

Alex Martelli aleaxit at yahoo.com
Fri Dec 8 04:09:14 EST 2000


"Greg Ewing" <greg at cosc.canterbury.ac.nz> wrote in message
news:3A30285A.46813B28 at cosc.canterbury.ac.nz...
    [snip]
> As a final refinement, you may want to enclose the
> operation in a try...finally, to make sure that the
> old value of stdout doesn't get lost if there is
> an exception raised while doing your stuff:
>
>   old_stdout = sys.stdout
>   sys.stdout = Tee( reportfile, sys.stdout )
>   try:
>     # do some stuff
>   finally:
>     sys.stdout = old_stdout

Very good, but, not _quite_ final... while in some versions
of Python object's finalizers are called just as soon as an
object's reference count goes to zero (and such versions
include the current 'CPython'), this is not a guaranteed
characteristic of the language -- in other versions (such as
Jython and Python .NET), finalization might be delayed or
even non-guaranteed.

If one can, therefore, it may be considered preferable to
finalize one's objects explicitly if that finalization matters
for other purposes than just making available the memory
the objects use -- closing files and tearing down database
connections being typical examples.

It may therefore be even better to change this finally
clause into a more elaborate one, for compatibility with
all Python dialects...:

    finally:
        try: sys.stdout.close()
        finally: sys.stdout = old_stdout

or even more, if one wants to hide exceptions that would
come if the Tee class doesn't define a close method, e.g:
    finally:
        try:
            closer = getattr(sys.stdout,'close',None)
            if not closer is None: closer()
        finally: sys.stdout = old_stdout
or
    finally:
        try:
            try: sys.stdout.close()
            except AttributeError: pass
        finally: sys.stdout = old_stdout


On the other hand, on the principle "do the simplest
thing you can possibly get away with", the much simpler
and cleaner form you use could be kept today, maybe
with just a comment about explicit finalization needing
to be added if this is ever ported to some Python
version without guarantee of immediate finalization
on reference count going to zero -- just to alert any
possibly-unaware-of-this-issue future maintainer!


Alex






More information about the Python-list mailing list