Code blocks, execution frames, and namespaces

Introduction

A code block is a piece of Python program text that can be executed as a unit, such as a module, a class definition or a function body. Some code blocks (like modules) are normally executed only once, others (like function bodies) may be executed many times. Code blocks may textually contain other code blocks. Code blocks may invoke other code blocks (that may or may not be textually contained in them) as part of their execution, e.g., by invoking (calling) a function.

Code block namespaces

Code Block TypeGlobal NamespaceLocal Namespace
Modulen.s. for the modulesame as global
Script (file or command)n.s. for __main__same as global
Interactive commandn.s. for __main__same as global
Class definitionglobal n.s. of containing blocknew namespace
Function bodyglobal n.s. of containing blocknew namespace
String passed to exec statementglobal n.s. of containing blocklocal namespace of containing block
String passed to eval()global n.s. of callerlocal n.s. of caller
File read by execfile()global n.s. of callerlocal n.s. of caller
Expression read by input()global n.s. of callerlocal n.s. of caller