310 likes | 833 Views
Scoping and Namespaces. CSIS 1595: Fundamentals of Programming and P roblem Solving 1. Namespaces. Namespace: List of all variables and their current values Maintained by Python environment Example:. Namespaces and Functions. Each function has different namespace
E N D
Scoping and Namespaces CSIS 1595: Fundamentals of Programming and Problem Solving 1
Namespaces • Namespace: • List of all variables and their current values • Maintained by Python environment • Example:
Namespaces and Functions • Each function has different namespace • Variable in function has no effect on same variable in any other function • Like two “separate universes” Spock in main program Spock in separate function
Arguments and Namespaces • Arguments to functions are also local to a namespace • Example: Fahrenheit to Celsius program • Note that f and c are differentin function, main program
Arguments and Namespaces • Key idea: Does not matter whether same or different variable names used in functions • Will be treated as different variables regardless • Example: Two versions of fahreheit2celsius program • Both do the same thing
Passing Arguments by Value • Key idea: • Variables not passed or returned • Only their values are passed/returned • In both cases the valueof 50 passed and the value of 10 returned
Namespaces and Functions • Why is this important? • Same function may be called from multiple places with different arguments • Example: “Largest of 4 numbers” program • Programs often created by hundredsof programmers • Each creates set of functions • Should not have to worry about what variables other programmers are using! • Functions often put in separate files (modules) • No main program associated with it!
Functions Calling Functions • Separate namespace created for each call
Activation Stack • Each current namespace = “activation record” • Maintained on “stack” of activation records • When function called, its namespace pushed on top of stack • When return from function, that namespace removed • Return to function immediately below it on stack
Stack for Population Program compute_population print_line compute_population print_line get_years print_table print_table print_table print_table print_table print_table print_table print_table Main program Main program Main program Main program Main program Main program Main program Main program Main program Main program Main program
Scoping • Key idea: Namespace only exists while function active • Scope of variable = function it is defined in • Does not exist outside of its scope(error if referenced)
Scoping and Global Variables • Exception: Functions may refer to variables in main • Exception to the exception: If value assignedin function it becomes local to function • Just avoid doing this! Prints 3 Still 3