Thursday, February 6, 2014

Week 5: Name Problems in Python

    At the beginning of learning to write functions, I find local variables very confusing. Through a period of study and this weeks' topic, I gained a deeper understanding about name matters. As follows I wrote down some points in order to remind myself.
    As I learned in Wednesday's lecture, every name in Python has a value and every value is a reference to an address of an object. Current module or '__main__' names are global names. It is visible to the whole module. Inside a function, the names are local names, which are only visible under the function. Outside the function, the name is not defined. But inside a function, we may use key word 'global' to define a name globally, or it is seen as local by default. In cases we define a function inside a function, we may use key word 'nonlocal' to get approach to the name in upper layers. python docs namespace example is a great help to understand them. Sometimes, names that seems to be same are totally different. Python reads local name first without 'global' 'nonlocal' or other key words. Also in Python there are some built-in names. When we write our own code, we should try to avoid using global names or built-in names. It may get messed if we use them.
    In term of names in class methods, child class sometimes overrides its super class. When we call a child class method that also appear in its super class, Python runs the method in the child class, no matter where the method call is(even inside a super class method call). Recursive functions are sometimes a little hard to trace, because in the stack frame(seen in visualizer), I find the same names appear many times and the frame repeated itself again and again. So in general, do not trace recursive functions too far.

def scope_test():
    def do_local():
        spam = "local spam"
    def do_nonlocal():
        nonlocal spam
        spam = "nonlocal spam"
    def do_global():
        global spam
        spam = "global spam"
    spam = "test spam"
    do_local()
    print("After local assignment:", spam)
    do_nonlocal()
    print("After nonlocal assignment:", spam)
    do_global()
    print("After global assignment:", spam)

scope_test()
print("In global scope:", spam)
# From http://docs.python.org/3.3/tutorial/classes.html#scopes-and-namespaces-example

   

4 comments:

  1. I found the example really helpful as it explains the order and "nonlocal", "global" method well.

    ReplyDelete
    Replies
    1. Right. The example covers almost all the possible situations.

      Delete
  2. The reading is really helpful!!

    ReplyDelete
    Replies
    1. Right. The example covers almost all the possible situations.

      Delete