Nested scopes: design or implementation?

mmillikan at vfa.com mmillikan at vfa.com
Wed Mar 6 17:23:11 EST 2002


"logistix" <logstx at bellatlantic.net> writes:

> Okay, now I'm confused.
> 
> I was perfectly happy with Teddy Reedy's explaination that def is an
> expression and not a declaration.
> 
> But if I'm following you, the embedded attribute function isn't being
> recompiled to bytecode each time function() is called.  If the code object
> is only getting created once, then why are the defaults getting
> recalculated?
> 
> --
> -
> 
> <mmillikan at vfa.com> wrote in message news:3czdq05v.fsf at vfa.com...
> > Note that the <func_code> object is shared by each of the inner
> > <function> objects:
> >
> > text = "random text"
> > def function():
> >     def attribute( bindNow = text):
> >         print bindNow
> >     function.attribute = attribute
> >
> > Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
> > Type "copyright", "credits" or "license" for more information.
> >
> > >>> function()
> > >>> function.attribute()
> > random text
> > >>> function.attribute
> > <function attribute at 01A7930C>
> > >>> function.attribute.func_code
> > <code object attribute at 01A79F48, file "c:\\python-YYAS0o", line 3>
> >
[snip]
> > >>> text = 'new random text'
> > >>> function()
> > >>> function.attribute
> > <function attribute at 01A450CC>
> > >>> function.attribute.func_code
> > <code object attribute at 01A79F48, file "c:\python-YYAS0o", line 3>
> >
> > Mark Millikan

In the example above notice that the function.attribute object is
recreated each time the outer definition is called -- it has a
different address.

However:

>>> import pprint
>>> pprint.pprint(dir(function.attribute))
['__dict__',
 '__doc__',
 '__name__',
 'func_closure',
 'func_code',
 'func_defaults',
 'func_dict',
 'func_doc',
 'func_globals',
 'func_name']
>>> function.attribute.func_defaults
('random text',)
>>> text = "new random text"
>>> function()
>>> function.attribute.func_defaults
('new random text',)

The func_code object is shared, but the function object is not. Each
of the function objects gets a separate func_defaults object. Some of
the state (the func_code object at least, is shared but some is not).

HTH
Mark Millikan



More information about the Python-list mailing list