Quirk difference between classes and functions

Peter J. Holzer hjp-python at hjp.at
Thu Feb 28 02:38:17 EST 2019

On 2019-02-27 12:34:37 -0500, Dennis Lee Bieber wrote:
> On Tue, 26 Feb 2019 19:15:16 -0800 (PST), jfong at ms4.hinet.net declaimed the
> following:
> >So, may I say that the Python compiler is a multi-pass one?
> 	No... that is implementation dependent...

True, but

> 	The common Python is a byte-code compiler pass (how many is undefined)
> which then feeds a byte-code INTERPRETER.

He's only talking about the byte-code compiler here, not the

> The compiler pass "sees" the local assignment, and creates a run-time
> data structure for the function which "holds" the local data.

Yup, but in

    def foo():
        bar = 1

the compiler sees the local assignment AFTER the print() call. So it
can't generate code to access the local variable for the print call
because it doesn't yet know that bar is a local variable.

The obvious way around this is a two pass compiler: In the first pass
you parse the whole function and convert it into an AST. While you do
this you can also collect local variables. In the second pass you
convert the AST to byte-code.

I think it should be possible to do it in a single pass, although at the
cost of generating less efficient code: For each variable access,
produce code to check for a local variable first, then a global one.
Collect information on local variables at the same time. When you are
done, generate the code to set up the local variables and arrange for it
to be executed before any other code in the function.


   _  | Peter J. Holzer    | we build much bigger, better disasters now
|_|_) |                    | because we have much more sophisticated
| |   | hjp at hjp.at         | management tools.
__/   | http://www.hjp.at/ | -- Ross Anderson <https://www.edge.org/>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20190228/d79089df/attachment.sig>

More information about the Python-list mailing list