“LEGB” order rule
L, Local — Names assigned in any way within a function (def or lambda)), and not declared global in that function.
E, Enclosing function locals — Name in the local scope of any and all enclosing functions (def or lambda), from inner to outer.
G, Global (module) — Names assigned at the top-level of a module file, or declared global in a def within the file.
B, Built-in (Python) — Names preassigned in the built-in names module : open,range,SyntaxError,…
Essentially, the only thing in Python that introduces a new scope is a function definition. Classes are a bit of a special case in that anything defined directly in the body is placed in the class’s namespace, but they are not directly accessible from within the methods (or nested classes) they contain.
Restrictions: Variables in scopes other than the local function’s variables can be accessed, but can’t be rebound to new parameters without further syntax. Instead, assignment will create a new local variable instead of affecting the variable in the parent scope.
In order to actually modify the bindings of global variables from within a function scope, you need to specify that the variable is global with the global keyword.
In Python 2 the list comprehension does not create a variable scope, however in Python 3 the loop variable is created in a new scope.
A full list of the built-in functions(76 totally) of Python(2) can be found here.
Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
Note the code above:
The “import” statement adds a module into the current globel scope;
This “del” statement can remove name from the current scope, including the default ones like “__builtins__”;
After you remove the default “__builtins__”, the built-in fuctions are unavailable.
And you can monkey patch the built-in functions as well.
1 2 3 4 5
What is the difference between an expression and a statement?
Expressions only contain identifiers, literals and operators, where operators include arithmetic and boolean operators, the function call operator “()” the subscription operator “” and similar, and can be reduced to some kind of “value”, which can be any Python object.
Statement, on the other hand, are everything that can make up a line (or several lines) of Python code. Note that expressions are statements as well.
In Python document, “lambda” is treated as expression.
1 2 3 4 5 6 7 8