你见过哪些令你瞠目结舌的Python代码技巧?

让我觉得瞠目结舌的要数这个Python库了,真是将import hook用到了极致:

lihaoyi/macropy · GitHub

你问我这个有什么屌的?

来来来,看几个例子:

更好用的lambda表达式

from macropy.quick_lambda import macros, f, _

print map(f[_ + 1], [1, 2, 3])    # [2, 3, 4]
print reduce(f[_ * _], [1, 2, 3]) # 6

代码跟踪

from macropy.tracing import macros, trace
with trace:
    sum = 0
    for i in range(0, 5):
        sum = sum + 5

输出:

sum = 0
for i in range(0, 5):
sum = sum + 5
range(0, 5) -> [0, 1, 2, 3, 4]
sum = sum + 5
sum + 5 -> 5
sum = sum + 5
sum + 5 -> 10
sum = sum + 5
sum + 5 -> 15
sum = sum + 5
sum + 5 -> 20
sum = sum + 5
sum + 5 -> 25

用个contextmanager就把block里的代码执行过程输出了

尾递归优化

from macropy.experimental.tco import macros, tco

@tco
def fact(n, acc=0):
    if n == 0:
        return acc
    else:
        return fact(n-1, n * acc)

print fact(10000)  # doesn't stack overflow
# 28462596809170545189064132121198688901...

模仿LINQ的PINQ

print sql[(
    x.name for x in db.country
    if x.gnp / x.population > (
        y.gnp / y.population for y in db.country
        if y.name == 'United Kingdom'
    ).as_scalar()
    if (x.continent == 'Europe')
)]

输出:

SELECT country_1.name
FROM country AS country_1
WHERE country_1.gnp / country_1.population > (SELECT country_2.gnp / country_2.population AS anon_1
FROM country AS country_2
WHERE country_2.name = ?) AND country_1.continent = ?

你可能感兴趣的:(python)