Page 81 -
P. 81

sharing your code


           Python’s modules implement namespaces


          All code in Python is associated with a namespace.
           Code in your main Python program (and within IDLE’s shell) is associated   That’s a double underscore in
           with a namespace called __main__. When you put your code into its own    front of the word “main” and
           module, Python automatically creates a namespace with the same name as   after it.
           your module. So, the code in your module is associated with a namespace
           called nester.


                                             I guess namespaces are like family names?
                                             If someone is looking for Chris, we need to know
                                             if it’s Chris Murray or Chris Larkin, right? The
                                             family name helps to qualify what we mean, as do
                                             namespace names in Python.









                                                      Yes, namespace names are like family names.
                                                      When you want to refer to some function from a module
                                                      namespace other than the one you are currently in, you need
                                                      to qualify the invocation of the function with the module’s
                                                      namespace name.
                                                      So, instead of invoking the function as print_lol(cast)
                                                      you need to qualify the name as nester.print_lol(cast).
                                                      That way, the Python interpreter knows where to look. The
                                                      format for namespace qualification is: the module’s name, followed
                                                      by a period, and then the function name.








                  The module name, which
                  identifies the namespace.                                    The function is then invoked as
                                            nester.print_lol(cast)             normal, with “cast” provided as
                                                                               the list to process.
                                                A period separates the module namespace
                                                name from the function name.



                                                                                       you are here 4    45
   76   77   78   79   80   81   82   83   84   85   86