Reading 7
Python Scope and the LEGB Rule: Resolving Names in Your Code
Some Definitions First
- Scope - the area of a program where you can access certain defined features
- LEGB - Local, Enclosing, Global, Built-in
- Local - params and names only available within the function code block or lambda in which they were defined
- Enclosing - also, non-local, only applies to nested functions, the enclosing scope is the outer function, and shares its names/params with the inner function
- Global - available everywhere in the code, begins the moment you start a python script
- Built-in - a special Python scope, is loaded whenever you run scripts, contains built-in keywords, functions, exceptions, etc.
The LEGB Rule determines the order in which Python will look up names. For example, if Python is checking for a variable name “foo” it first looks locally in the function where it is required, then to the Enclosing function, if applicable, then to the global variable list, then to the Built-in list. Thus, it is important to know where the name resides to ensure it will be accessed properly and won’t be modified unintentionally.
Assigning a variable does one of two things: 1) creates a new name or 2) updates existing name
## Don’t Be Confused by BigO Notation
In short, BigO is how complex an algorithm is. Why is this important?
In terms of time, does the algorithm respond well to increasing amount of data? In terms of space, will the computer run out of memory when you run an algorithm using a data set?
Scaling is an extremely important factor to consider when designing an algorithm and BigO categorizes that scaled performance.
source: https://upload.wikimedia.org/wikipedia/commons/thumb/7/7e/Comparison_computational_complexity.svg/1920px-Comparison_computational_complexity.svg.png
As you can see in the chart above, as number of operations is scaled up, the performance will be determined by the manner in which the algorithm is created. An O(1) algorithm maintains consistent performance as the data set is scaled up, whereas a O(n!) algorithm would quickly run into time and space complexity problems.