1

On the SaltyCraneBlog (http://www.saltycrane.com/blog/2008/01/python-variable-scope-notes/#c7900), I was reading up on the variable scope in Python and everything was all pretty straightforward, until I got this workaround for setting global variables:

def ex8():
    ex8.var = 'foo'
    def inner():
        ex8.var = 'bar'
        print 'inside inner, ex8.var is ', ex8.var
    inner()
    print 'inside outer function, ex8.var is ', ex8.var
ex8()

What's throwing me off is the ex8.var part. Is this an attribute? If var is an attribute of ex8, wouldn't var need to be defined first? Can a function's attributes be called within the function itself?

1 Answer 1

1

What's throwing me off is the ex8.var part. Is this an attribute?

Yes.

If var is an attribute of ex8, wouldn't var need to be defined first?

No. You can set attributes on objects any time you want, without predeclaring them (unless the object defines special behavior preventing you from doing that).

Can a function's attributes be called within the function itself?

Yes, a function's attributes can be accessed from within the function. The function is an object like an other and you can access attributes of it as you can for any other object accessible in the current scope. (The attribute is not "called" here, since its value is not a function; it's just a value that you access.)

As the comment you linked to mentions, what this code is doing is not necessarily a good thing to do. As mention in that blog post, Python 3 includes a nonlocal keyword that removes the need for such hackery. Even in Python 2, it is not common to find yourself in a situation where you need to resort to such tricks.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.