mirror of
https://github.com/erg-lang/erg.git
synced 2025-09-29 20:34:44 +00:00
88 lines
2.8 KiB
Markdown
88 lines
2.8 KiB
Markdown
# Pythonとの連携
|
|
|
|
[](https://gezf7g7pd5.execute-api.ap-northeast-1.amazonaws.com/default/source_up_to_date?owner=erg-lang&repos=erg&ref=main&path=doc/EN/syntax/32_integration_with_Python.md&commit_hash=0d05a715f8e9d5f70d64fbd5b35b4651eb6aa1d6)
|
|
|
|
## Pythonへのexport
|
|
|
|
Ergスクリプトをコンパイルすると.pycファイルが生成されますが、これは単純にPythonのモジュールとして読み込むことができます。
|
|
ただし、Erg側で非公開に設定した変数はPythonからもアクセスできません。
|
|
|
|
```python
|
|
# foo.er
|
|
.public = "this is a public variable"
|
|
private = "this is a private variable"
|
|
```
|
|
|
|
```console
|
|
erg --compile foo.er
|
|
```
|
|
|
|
```python
|
|
import foo
|
|
|
|
print(foo.public)
|
|
print(foo.private) # AttributeError:
|
|
```
|
|
|
|
## Pythonからのimport
|
|
|
|
Pythonから取り込んだオブジェクトはデフォルトですべて`Object`型になります。このままでは比較もできないので、型の絞り込みを行う必要があります。
|
|
|
|
## 標準ライブラリの型指定
|
|
|
|
Python標準ライブラリにあるAPIはすべてErg開発チームにより型が指定されています。
|
|
|
|
```python
|
|
time = pyimport "time"
|
|
time.sleep! 1
|
|
```
|
|
|
|
## ユーザースクリプトの型指定
|
|
|
|
Pythonの`foo`モジュールに型を付ける`foo.d.er`ファイルを作成します。
|
|
Python側でのtype hintは100%の保証にならないので無視されます。
|
|
|
|
```python
|
|
# foo.py
|
|
X = ...
|
|
def bar(x):
|
|
...
|
|
def baz():
|
|
...
|
|
class C:
|
|
...
|
|
```
|
|
|
|
```python
|
|
# foo.d.er
|
|
.X: Int
|
|
.bar!: Int => Int
|
|
.foo! = baz!: () => Int # aliasing
|
|
.C!: Class
|
|
```
|
|
|
|
`d.er`内では宣言と定義(エイリアシング)以外の構文は使えません。
|
|
|
|
Pythonの関数はすべてプロシージャとして、クラスはすべて可変クラスとしてしか登録できないことに注意してください。
|
|
|
|
```python
|
|
foo = pyimport "foo"
|
|
assert foo.bar!(1) in Int
|
|
```
|
|
|
|
これは、実行時に型チェックを行うことで型安全性を担保しています。チェック機構は概念的には以下のように動作します。
|
|
|
|
```python
|
|
decl_proc proc!: Proc, T =
|
|
x =>
|
|
assert x in T.Input
|
|
y = proc!(x)
|
|
assert y in T.Output
|
|
y
|
|
```
|
|
|
|
これは実行時オーバーヘッドとなるので、PythonスクリプトをErgの型システムで静的に型解析するプロジェクトが計画されています。
|
|
|
|
<p align='center'>
|
|
<a href='./31_pipeline.md'>Previous</a> | <a href='./33_package_system.md'>Next</a>
|
|
</p>
|