Monday, 25 November 2013

Blog Entry #8: Namespaces

Blog Entry #8: Namespaces

         Namespaces are the fundamental idea in Python. I used global names a few time when I try to update the a variable inside a function. After this week's lecture, I realize I did not completely understand this concept in the past, so I did a little bit research on namespaces to improve my understanding. In this blog post, I will briefly talked about what I have learned from the lecture and research.

          One advantage in Python is that you can apply a name to any variable, unlike in other languages such as Java you are required to define the type of the variable first. You can assign the same name to a value and a function, and Python can recognize the type when you call the name.

          For example:
          var = 148
          var =  "I love CSC148"
          var = ["I", "love", "CSC", 148]
          def var():
                ...

          According to the Python tutorial, a namespaces is a space that holds a number of names. They are a mapping from names to objects. Each namespaces is completed isolated. Similar to the example above demonstrates, you can have a module called  Integer and a module called Float and both could have a function named calculate().  You can access the names using prefix such has Integer.calculate() or Float.calculate().

          Another useful concept is scoping. A scope refers to "a region of a program from where a namespace can be accessed without a prefix". Namespaces are also searched for names inside out. If there's a certain name declared in the module's global namespace, it can be reused inside the function.

         Python looks from the innermost scope, which is usually a function, enclosing scopes, global (__main__), to built-in names. You can force the program to access the name by prefixing the name with keywords such as global.