Namespace

  • maps names to objects
  • internally a dictionary (key, value)
    • key => object name
    • value => the object itself
    • four types of namespace
      • built-n; global; local; enclosing (later)

Scope

- global namespace for global scope
    - globals()
- local namespace for each local scope
    - locals()
- builtin namespace for builtin scope
paints = ["red", "blue", "green"]
myfavorite = "pink"

print(globals())
print("-" * 60)

def color_room(myfavorite):
    print(myfavorite)
    if myfavorite in paints:
        print("you are in luck")
    print("LOCALS:", locals())
    print("-" * 60)

def add_color(newcolor):
    paints.append(newcolor)
    paints.append(myfavorite) # what happens?
    print("LOCALS:", locals())
    print("-" * 60)

print(globals())
print("-" * 60)  

color_room("purple")
color_room("blue")
add_color("yellow")

more on import and modules

  • module contents are in a separte namespace
  • dir()
    • list of defined names in a namespace
    • dir(object) object can be imported module

More about namespace

loading a module:
- a module object is created and inserted in sys.modules
- module object is a namespace that has definitions from the module
- adds module object to the global namespace
- dir() or dir(module_name)
- the code of the module is executed
- if module imported >1, only executed one
- a module object contains the definitions from the module

  • packages: collection of related modules that provide some functionality. Will contain __init__ to indicate a package.
  • library: bundle of code, can have 100s of modules
  • Python standard library: comes with your installation of Python