python namespaces - ghdrako/doc_snipets GitHub Wiki

Built-ins level

When Python starts running an application, it creates a builtins namespace where builtins is the outermost namespace in Python and contains all of the functions you can access at any time. For example, the print() and open() functions exist in the builtins namespace.

Show what’s in the builtins namespace:

>>> dir(__builtins__)

it’s entirely possible to overwrite an object in a namespace with something of your own. For example, you could define a function like this:

def open(…):
# run some code here

Creating a function like this would be perfectly fine; however, the side effect of doing this is shadowing the open() function that’s already defined in the builtins namespace.

You can handle this by creating your function as follows:

def my_own_open(…):
# run some code here

Module level

Each Python code file creates a namespace for your use.

utility.py:
def add(a, b):
return f"{a} {b}"
 main.py:
import utility
def add(a, b):
return a + b
print(add(12, 12))
print(utility.add(12, 12))

Be aware that the namespace created by importing a file adds a namespace based on the base name of the file, which is the default behavior. You can override this default behavior in this way:

import utility as utils

This statement tells Python to pull all the objects in the utility.py file into a namespace called utils. Being able to alias the namespace specifically can be a useful feature if you want to import two modules with the same name but maintain a unique namespace for each. It’s also possible to mask a namespace when importing functionality. Using your current main.py example, it is done like this:

from utility import *
def add(a, b):
return a + b
print(add(12, 12))
print(utility.add(12, 12)) # error utility namespace not exist but if remove utility add function from main.py shadow function from utility.py

Function level

prefix = "added"
def add(a, b):
  prefix = "inside add function"
  return f"{prefix}: {a} {b}"