Python中的quasiquotation
项目描述
在Python代码中穿插非Python代码块以增加风味。
什么是quasiquote
quasiquote是一个新的语法元素,允许我们将非Python代码嵌入到现有的Python代码中。其基本结构如下
# coding: quasiquotes
[$name|some code goes here|]
这将简化为
name.quote_expr("some code goes here", frame, col_offset)
其中 frame 是执行栈帧,而 col_offset 是quasiquote的列偏移。
这允许我们使用更简洁的语法来编写代码。需要使用 # coding: quasiquotes 来启用此扩展。语法选择与GHC 6.12中的Haskell的quasiquote语法相匹配。我们需要使用旧语法(带有 $),因为Python的语法在没有它的情况下在引号开启步骤中将是模糊的。为了简化分词器,我们选择使用稍微冗长的语法。
我们还可以在修改后的with块中使用语句语法来为quasiquote编写语句
# coding: quasiquotes
with $name:
some code goes here
这将简化为
name.quote_stmt(" some code goes here", frame, col_offset)
c quasiquoter
内置的 c quasiquoter允许我们在Python中内联C代码。例如
>>> from quasiquotes.c import c
>>> def f(a):
... with $c:
... printf("%ld\n", PyLong_AsLong(a));
... a = Py_None;
... Py_INCREF(a);
... print(a)
...
>>> f(0)
0
None
>>> f(1)
1
None
在这里,我们可以看到quasiquote可以读取和写入局部作用域。
我们还可以使用引号表达式语法来引用C表达式。
>>> def cell_new(n):
... return [$c|PyCell_New(n);]
...
>>> cell_new(1)
<cell at 0x7f8dde6cd5e8: int object at 0x7f8ddf956780>
在这里,我们可以看到c quasiquoter作为一个Python接口到C API非常方便。
IPython 集成
我们可以在 IPython 交互式解释器或笔记本中使用 c 伪引号作为单元格或行魔术。当用作行魔术时,它作为表达式引用。当用作单元格魔术时,它作为语句引用。
In [1]: import quasiquotes.c
In [2]: a = 5
In [3]: %c PyObject *b = PyLong_FromLong(3); PyObject *ret = PyNumber_Add(a, b); Py_DECRE F(b); ret;
Out[3]: 8
In [4]: %%c
...: printf("%ld + %ld = %ld\n", 3, PyLong_AsLong(a), PyLong_AsLong(_3));
...: puts("reassigning 'a'");
...: a = Py_None;
...: Py_INCREF(a);
...:
3 + 5 = 8
reassigning 'a'
In [5]: a is None
Out[5]: True
项目详情
关闭
quasiquotes-0.2.0.tar.gz 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 579f8880beda026eb27b8c575abd4d5e1021e8be30706491ac5aea2d654ffb9b |
|
MD5 | 946c53e9ecda015d66b2b6423355c3b3 |
|
BLAKE2b-256 | bd2299bd423313a38d8b29ddd43a716c51b3f5a407f589837a4ebaec6154e840 |