object query assigned variable name?

Piet van Oostrum piet at cs.uu.nl
Wed May 6 07:57:26 EDT 2009

>>>>> John O'Hagan <research at johnohagan.com> (JO) wrote:

>JO> I guess what I meant was that if I type:

>JO> brian = Brian()

>JO> in the python shell and then hit return, it seems to me that
>JO> _somewhere_ (in the interpreter? I have no idea how it's done) it
>JO> must be written that the new Brian object will later be assigned
>JO> the name "brian", even as the process of creating the instance
>JO> begins. As you've just demonstrated, the actual assignment occurs
>JO> afterwards.

No, that's not how it works. There is no `preparation' for the
assignment and there is no reason for it. Look at the generated
byte code for this Python code:

def test():
    class Brian:
        def __init__(self):
            print "I'm Brian!"
    brian = Brian()

2           0 LOAD_CONST               1 ('Brian')
              3 LOAD_CONST               3 (())
              6 LOAD_CONST               2 (<code object Brian at 0x35728, file "<stdin>", line 2>)
              9 MAKE_FUNCTION            0
             12 CALL_FUNCTION            0
             15 BUILD_CLASS         
             16 STORE_FAST               0 (Brian)

  5          19 LOAD_FAST                0 (Brian)
             22 CALL_FUNCTION            0
             25 STORE_FAST               1 (brian)
             28 LOAD_CONST               0 (None)
             31 RETURN_VALUE        

You can see that the assignment (STORE_FAST) is done after the method
call (CALL_FUNCTION) and there is no reference to the variable name
before the call.

If you do a parallel assignment the relationship becomes even less:

brian, test = Brian(), 1

  5          19 LOAD_FAST                0 (Brian)
             22 CALL_FUNCTION            0
             25 LOAD_CONST               3 (1)
             28 ROT_TWO             
             29 STORE_FAST               1 (brian)
             32 STORE_FAST               2 (test)

Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org

More information about the Python-list mailing list