python dive into

__name__ of module

multiple = 1024 if a_is_1024 else 1000

 list comprehension

S = [2 * x for x in range(101) if x ** 2 > 3]

 dictionary comprehension

[(f, os.stat(f)) for f in glob.glob('*test*.py')]
#dictionary comprehension
{f:os.stat(f) for f in glob.glob('*test*.py')} 
s = {key: val for key, val in enumerate('ABCD') if val not in 'CB'}

set comprehension

s = {v for v in 'ABCDABCD' if v not in 'CB'}
>>> query = 'user=pilgrim&database=master&password=PapayaWhip'
>>> a_list = query.split('&')                                        
>>> a_list
['user=pilgrim', 'database=master', 'password=PapayaWhip']
>>> a_list_of_lists = [v.split('=', 1) for v in a_list if '=' in v]  
>>> a_list_of_lists
[['user', 'pilgrim'], ['database', 'master'], ['password', 'PapayaWhip']]
>>> a_dict = dict(a_list_of_lists)                                   
>>> a_dict
{'password': 'PapayaWhip', 'user': 'pilgrim', 'database': 'master'}

The pass statement in Python is like a empty set of curly braces ({}) in Java or C.

 

define private:

add "__" in front of the variable and function name can hide them when accessing them from out of class.

 

*args : variable length argument list

**kwargs : keyworded variable length of arguments

 

Closure:

Python supports a feature called function closures which means that inner functions defined in non-global scope remember what their enclosing namespaces looked like at definition time. This can be seen by looking at the func_closure attribute of our inner function which contains the variables in the enclosing scopes.

Variable resolve

1 basic rule
x = "foo"
def f():
    print x
    x = 5
f()

UnboundLocalError : since x is a local variable.

x = "foo"
def f():
    if some_condition:
        x = 42
    print x
f()

x still a local varialbe, maybe not assignment(init), depends on some_condition.

2 class-level scope

we want expressions like x = x to work, capturing the global variable x into class-level scope.

it will looks up in the module globals. it doesn't follow the chain of nested scopes.

x = "foo"

class Z:
    for i in range(2):
        print (x)    # prints the global x the 1st time, and 42 the 2nd time
        x = 42
class Y:
    if some_condition:
        x = 42
    print x     # may refer to either the local x, or some global x

A key difference is that 

statements and expressions in the body of a function are evaluated when the fuction is called.

the statements and expressions in the body of a class statement are executed as part of the class statement(earlier.)

In the function, some_condition may or may not be true, so x needs to have the same scope each time.

The class statement is executed once, so by the time print x is reached, we know if x is local or global by the time we reach it.

like javascript engine to resolve free variable.

http://www.python.org/dev/peps/pep-0227/ 

 

However, CPython has optimized some scenarios, specifically function locals. These optimizations, together with how the compiler and evaluation loop interact and historical precedent, lead to the confusion.

Python translates code to bytecodes, and those are then interpreted by a interpreter loop. The 'regular' opcode for accessing a name is LOAD_NAME, which looks up a variable name as you would in a dictionary. LOAD_NAME will first look up a name as a local, and if that fails, looks for a global.LOAD_NAME throws a NameError exception when the name is not found.

For nested scopes, looking up names outside of the current scope is implemented using closures; if a name is not assigned to but is available in a nested (not global) scope, then such values are handled as a closure. This is needed because a parent scope can hold different values for a given name at different times; two calls to a parent function can lead to different closure values. So Python has LOAD_CLOSURE,MAKE_CLOSURE and LOAD_DEREF opcodes for that situation; the first two opcodes are used in loading and creating a closure for a nested scope, and the LOAD_DEREF will load the closed-over value when the nested scope needs it.

Now, LOAD_NAME is relatively slow; it will consult two dictionaries, which means it has to hash the key first and run a few equality tests (if the name wasn't interned). If the name isn't local, then it has to do this again for a global. For functions, that can potentially be called tens of thousands of times, this can get tedious fast. So function locals have special opcodes. Loading a local name is implemented byLOAD_FAST, which looks up local variables by index in a special local names array. This is much faster, but it does require that the compiler first has to see if a name is a local and not global. To still be able to look up global names, another opcode LOAD_GLOBAL is used. The compiler explicitly optimizes for this case to generate the special opcodes. LOAD_FAST will throw an UnboundLocalError exception when there is not yet a value for the name.

Class definition bodies on the other hand, although they are treated much like a function, do not get this optimization step. Class definitions are not meant to be called all that often; most modules create classesonce, when imported. Class scopes don't count when nesting either, so the rules are simpler. As a result, class definition bodies do not act like functions when you start mixing scopes up a little.

So, for non-function scopes, LOAD_NAME and LOAD_DEREF are used for locals and globals, and for closures, respectively. For functions, LOAD_FASTLOAD_GLOBAL and LOAD_DEREF are used instead.

 

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. 

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print(n, 'equals', x, '*', n//x)
...             break
...     else:
...         # loop fell through without finding a factor
...         print(n, 'is a prime number')

 

 

posted on 2014-01-01 20:19  grep  阅读(228)  评论(0编辑  收藏  举报