Skip to content

Commit 3e128c9

Browse files
authored
docs: Add python block usage examples (#687)
* added some text * updated with input/output syntax
1 parent efa5464 commit 3e128c9

File tree

1 file changed

+47
-1
lines changed

1 file changed

+47
-1
lines changed

docs/src/pythoncall.md

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ This package is in the general registry, so to install just type `]` in the Juli
88
pkg> add PythonCall
99
```
1010

11-
## Getting started
11+
## [Getting started](@id py_getting_started)
1212

1313
Import the module with:
1414

@@ -91,6 +91,52 @@ Python: ValueError('some error')
9191
With the functions introduced so far, you have access to the vast majority of Python's
9292
functionality.
9393

94+
## Executing Python scripts
95+
96+
A common use case is calling multiple blocks of Python code from Julia interactively. This can be accomplished in PythonCall via the [@pyexec](@ref) macro. For example, the sentence parsing application in the [Getting started](@ref py_getting_started) section could be rewritten as:
97+
98+
```julia-repl
99+
julia> @pyexec """
100+
global re
101+
import re
102+
103+
def my_sentence(s):
104+
words = re.findall("[a-zA-Z]+", s)
105+
sentence = " ".join(words)
106+
return sentence
107+
""" => my_sentence
108+
Python: <function my_sentence at 0x7d83bb1b01a0>
109+
110+
julia> sentence = my_sentence("PythonCall.jl is very useful!")
111+
Python: 'PythonCall jl is very useful'
112+
```
113+
114+
Note the use of the `global` keyword to make the `re` package accessible in global scope, and the `=> my_sentence` syntax to create a Julia function named `my_sentence` that calls to the Python function of the same name. This syntax also supports calling to multiple functions and passing data back-and-forth:
115+
116+
```julia-repl
117+
julia> @pyexec (num=10) => """
118+
def add(a, b):
119+
return a + b
120+
121+
def subtract(a, b):
122+
return a - b
123+
124+
plusone = num + 1
125+
""" => (add, subtract, plusone::Float64)
126+
(add = <py function add at 0x721b001a7cc0>, subtract = <py function subtract at 0x721b001a7d70>, plusone = 11.0)
127+
128+
julia> add(4, 3)
129+
Python: 7
130+
131+
julia> subtract(4, 3)
132+
Python: 1
133+
134+
julia> plusone
135+
11.0
136+
```
137+
138+
Here we demonstrate passing a named variable, `num`, via the use of the `=>` syntax again, and returning named output, with the last element, `plusone`, being cast to a Julia object via the `::` syntax. See [@pyexec](@ref), [@pyeval](@ref), and their functional forms [pyexec](@ref) and [pyeval](@ref), for more.
139+
94140
## Conversion between Julia and Python
95141

96142
A Julia object can be converted to a Python one either explicitly (such as `Py(x)`) or

0 commit comments

Comments
 (0)