Why is the use of an undefined name not a syntax error?

Chris Angelico rosuav at gmail.com
Sun Apr 1 17:38:07 EDT 2018


On Mon, Apr 2, 2018 at 7:24 AM, David Foster <davidfstr at gmail.com> wrote:
> My understanding is that the Python interpreter already has enough information when bytecode-compiling a .py file to determine which names correspond to local variables in functions. That suggests it has enough information to identify all valid names in a .py file and in particular to identify which names are not valid.
>

It's not as simple as you think. Here's a demo. Using all of the
information available to the compiler, tell me which of these names
are valid and which are not:


import sys

def search_file(fn):
    with open(fn) as f:
        for line in f:
            if "spam" in line and len(line) < 80:
                print("Mmmm delicious spam")

if __name__ == "__main__":
    try:
        search_file(sys.argv[1])
    except IndexError:
        print("Please provide a file name", file=sys.stderr)
    except FileNotFoundError:
        print("File not found", file=sys.stderr)
    except OSError as Exception:
        print("Error %d reading file: %s" %
            (Exception.errno, Exception.strerror))
    except Exception:
        print("Something else went wrong:")
        import traceback
        traceback.print_exc()
    finally:
        print("Goodbye.")


Okay. Reckon you got them all? Look again  there's probably at least
one sneaky one that you missed. List them for me, and tell me what's
valid and what's not.

ChrisA


More information about the Python-list mailing list