diff --git a/docs/src/pythoncall.md b/docs/src/pythoncall.md index a4f191e8..44153a70 100644 --- a/docs/src/pythoncall.md +++ b/docs/src/pythoncall.md @@ -8,7 +8,7 @@ This package is in the general registry, so to install just type `]` in the Juli pkg> add PythonCall ``` -## Getting started +## [Getting started](@id py_getting_started) Import the module with: @@ -91,6 +91,52 @@ Python: ValueError('some error') With the functions introduced so far, you have access to the vast majority of Python's functionality. +## Executing Python scripts + +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: + +```julia-repl +julia> @pyexec """ + global re + import re + + def my_sentence(s): + words = re.findall("[a-zA-Z]+", s) + sentence = " ".join(words) + return sentence + """ => my_sentence +Python: + +julia> sentence = my_sentence("PythonCall.jl is very useful!") +Python: 'PythonCall jl is very useful' +``` + +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: + +```julia-repl +julia> @pyexec (num=10) => """ + def add(a, b): + return a + b + + def subtract(a, b): + return a - b + + plusone = num + 1 + """ => (add, subtract, plusone::Float64) +(add = , subtract = , plusone = 11.0) + +julia> add(4, 3) +Python: 7 + +julia> subtract(4, 3) +Python: 1 + +julia> plusone +11.0 +``` + +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. + ## Conversion between Julia and Python A Julia object can be converted to a Python one either explicitly (such as `Py(x)`) or