function attributes are like function objects

Tim Peters tim.one at home.com
Sat Feb 3 03:17:21 EST 2001


[Geoffrey Gerrietts]
> ...
> I just want to avoid losing the point; is the function going to have
> access to this bit of state its carrying around,

No.

> or is that reserved for outside parties?

Also no.  I know you don't want to hear about namespace issues, but those
*are* the issues here.  As Aahz said, there is no form of "self" for
function objects (or class objects, or file objects, or list objects, or
...).  The only way to get to the attr is via the object, for functions as
for everything else.  Whether you're "in" or "out" of the function makes no
difference to that.  Visibility of names is the entire story in both cases.

>>> def f():
...     print "f.a is", f.a
>>> f.a = 42
>>> f()
f.a is 42
>>

But if-- for whatever reason --the name of "f" is not visible inside the
body of "f", that won't work, and there's no special syntax then that can
make it work.  For example, run this under 2.1a2:

def f():
    def f():
        print "inner f.a is", f.a
    f.a = 666
    f()
    print "outer f.a is", f.a
f.a = 42
f()

Both "print" stmts see the inner redefinition of f then, so both references
to "f.a" yield 666.  But that's mondo perverse code!

don't-punch-yourself-in-the-throat-and-you-won't-gag-ly y'rs  - tim





More information about the Python-list mailing list