DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

Coconut Notes


Install

Conda

使用 Conda 安装 Coconut 无法包含附加组件,例如 --watch, --mypy 等。

$ conda create -n coconda python=3.6
$ . activate coconda
$ conda install -c conda-forget coconut

Pip

$ conda create -n coco python=3.6
$ . activate coco
$ pip install 'coconut[all]'

注意安装时 coconut[all] 外面的单引号不能省略,否则中括号会被 zsh 解释从而导致错误。 另外如果安装速度特别慢,可以在早晨7点前安装,这个时段网络速度最快。

REPL Workflow

下面的例子演示了 IPython 中的 Python 和 Coconut 混合编程, 启动 IPython REPL 后加载 Coconut 扩展,其功能包括:

  • 解析 %c 和 %%c 并即时编译为 Python 代码并运行;

  • 执行 import mylib 时,如果只有 mylib.coco 没有 mylib.py,先编译为 py 再 import;

转换并执行后,可以通过双问号查看转换后的 Python 代码(例如下面的 myswitch??), 从而实现了与 Python 环境的无缝融合:

$ ipython
>>> %load_ext coconut
>>> %alias_magic c coconut
>>> a = 5
>>> %c a |> print
5
>>> %c dubsums = map((x, y) -> 2*(x+y), range(0, 10), range(10, 20)) |> list
>>> print(dubsums)
[20, 24, 28, 32, 36, 40, 44, 48, 52, 56]
>>> %c dubsums |> print
[20, 24, 28, 32, 36, 40, 44, 48, 52, 56]
>>> %%c
..: def myswitch(inp: float) -> float:
..:     case inp:
..:         match d is float if d > 10:
..:             print('d is > 10')
..:             return d
..:         match d is int if inp < 5:
..:             print('less than 5')
..:             return d * 2
..:     else:
..:         print("nothing found")
..:         return inp + 10
..:     return 0
>>> myswitch??
# the converted Python codes
>>> myswitch(43)
nothing found
53
myswitch(23.3)
d is > 10
23.3

Coconut 有自己的 REPL,但不支持变量名称和对象方法的 tab-completion,可用性比较差。

IPython Autoload Extension

每次使用 IPython console 都要手工输入一堆代码比较麻烦,下面的配置自动化了这个流程: 首先创建新的配置文件:

ipython profile create coconut
vi ~/.ipython/profile_coconut/ipython_config.py

然后在此文件中添加如下内容就可以了:

c.InteractiveShellApp.exec_lines = [
    '%alias_magic c coconut',
    'import pandas as pd',
    'import numpy as np'
]

c.InteractiveShellApp.extensions = [ 'coconut' ]

使用 . activate coco; ipython --profile coconut 启动。

Ref:

  • ipython profile --help

  • Code examples: https://ipython.readthedocs.io/en/stable/config/intro.html

Module Definition and Loading

Coconut 文件扩展名为 coco,模块定义、import 方法与 Python 完全一致。 一个 .coco 文件 import 另一个 .coco 文件时, 被导入的模块会先被编译为 Python(.py 和 .pyc)文件然后加载。



Published

Jan 29, 2019

Last Updated

Jan 31, 2019

Category

Tech

Tags

  • coconut 1

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor