3

突然想到 py 一个简单的函数字符串缩写语法糖,不知道有没有现成的?

 2 years ago
source link: https://www.v2ex.com/t/794383
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  Python

突然想到 py 一个简单的函数字符串缩写语法糖,不知道有没有现成的?

  O5oz6z3 · 4 小时 46 分钟前 · 399 次点击
import magic

# 1 lambda 匿名函数表达式识别:没有分号`;`或者无括号参数声明 `args:`
magic | "_: _.attr+1"
magic | "*a,**k: a[0].attr+1"

# 2 def 多行函数识别:检测分号`;`或者括号参数声明`(args):`或者函数声明`def (args):` 
magic | "_.attr+= 1; yield _.attr"
magic | "(*a,**k): b=a[0].attr+1; yield b"
magic | "def(*a,**k): b=a[0].attr+1; yield b"
magic | "def *a,**k: b=a[0].attr+1; yield b"

# 3 传递位置参数引用:等价于 partial(func, *args),参数从左侧开始绑定。
magic | ["a,b: a+b", a, b]

# 4 传递关键字参数引用:等价于 partial(func, **kwrds)
magic("a,b,c=None: c or a+b", c=c)

# 5 同时传递位置参数和关键字参数引用:等价于 partial(func, *args, **kwrds)
magic("a,b,c=None: c or a+b", a, b, c=c)

# 6 隐式参数:`_`
magic | "_.attr+1"
magic | "def: b=_.attr+1; yield b"

突然想到这么一个简单的语法糖格式,不知道是否已经被人提出实现过了?还是说这种魔法语法糖没有实用价值?那么有没有类似的纯字符串 DSL 语法糖库?或者大家有什么其他看法?

原理是将多行函数或函数表达式的缩写写在字符串里,然后构造出函数。

实现思路是简单地检测字符串,也可以用正则,甚至手写解释器。 转换回完整 python 函数也简单,补充完整函数声明然后 eval/exec 。

缺点是传值、闭包引用会比较麻烦,虽然应该可以通过 inspect 实现,但这么复杂和不纯函数不建议用字符串缩写。如果是完整的函数代码字符串,那根本就不需要缩写了。

优点是导入即可使用。而且可以进一步拓展支持自定义的函数语法糖格式。比方说想要更好可读性的语法糖,只要实现了对应 DSL 字符串转化为 python 函数的解释器就可以了。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK