Skip to main content

Interacting with Python

ScalaPy offers a variety of ways to interact with the Python interpreter, enabling you to calculate any Python expression from Scala code.

Global Scope#

The primary entrypoint into the Python interpreter from ScalaPy is, which acts similarly to Scala.js's to provide a dynamically-typed interface for the interpreter's global scope. With, you can call any global method and access any global value.

For example, we can create a Python range with the range() method, and calculate the sum of its elements with sum().

// Python ranges are exclusive
val list =, 3 + 1)
// list: py.Dynamic = range(1, 4)
// 1 + 2 + 3 == 6
val listSum =
// listSum: py.Dynamic = 6

Importing Modules#

If you're working with a Python library, you'll likely need to import some modules. You can do this in ScalaPy with the py.module method. This method returns an object representing the imported module, which can be used just like but with the contents referencing the module instead of the global scope.

For example we can import NumPy, a popular package for scientific computing with Python.

val np = py.module("numpy")
// np: py.Module = <module 'numpy' from '/opt/buildhome/.pyenv/versions/3.7.1/lib/python3.7/site-packages/numpy/'>
val a = np.array(Seq(
Seq(1, 0),
Seq(0, 12)
// a: py.Dynamic = [[ 1 0]
// [ 0 12]]
val aSquared = np.matmul(a, a)
// aSquared: py.Dynamic = [[ 1 0]
// [ 0 144]]

Scala-Python Conversions#

In the previous example, you'll notice that we passed in a Scala Seq[Seq[Int]] into np.array, which usually takes a Python list. When using Python APIs, ScalaPy will automatically convert scalar Scala values into their Python equivalents (through the Writer type). This handles the integer values, but not sequences, which have multiple options for conversion in ScalaPy.

If you'd like to create a copy of the sequence, which can be accessed by Python code with high performance but miss any mutations you later make in Scala code, you can use toPythonCopy:

val mySeqToCopy = Seq(Seq(1, 2), Seq(3))
// mySeqToCopy: Seq[Seq[Int]] = List(List(1, 2), List(3))
// res0: py.Any = [[1, 2], [3]]

If you'd like to create a proxy of the sequence instead, which uses less memory and can observe mutations but comes with a larger overhead for repeated access from Python, you can use toPythonCopy:

val mySeqToProxy = Array(1, 2, 3)
// mySeqToProxy: Array[Int] = Array(1, 2, 100)
val myProxy = mySeqToProxy.toPythonProxy
// myProxy: py.Any = <SequenceProxy object at 0x7fc72bf4a860>
// [1, 2, 3]
mySeqToProxy(2) = 100
// [1, 2, 100]

To convert Python values back into their Scala equivalents, ScalaPy comes with the .as API to automatically perform conversions for supported types (those that have a Reader implementation). Unlike writing, where there were multiple options for converting sequence types, there is a single .as[] API for converting back. If you load a collection into an immutable Scala sequence type, it will be loaded as a copy. If you load it as a mutable.Seq, however, it will be loaded as a proxy and can observe underlying changes

import scala.collection.mutable
val myPythonList =
// myPythonList: py.Dynamic = [200, 1, 2, 3, 4, 5, 6, 7, 8, 9]
val copyLoad =[Vector[Int]]
// copyLoad: Vector[Int] = Vector(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
val proxyLoad =[mutable.Seq[Int]]
// proxyLoad: mutable.Seq[Int] = Seq(200, 1, 2, 3, 4, 5, 6, 7, 8, 9)
// Vector(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
// Seq(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
myPythonList.bracketUpdate(0, 100)
// Vector(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
// Seq(100, 1, 2, 3, 4, 5, 6, 7, 8, 9)
proxyLoad(0) = 200
// [200, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Custom Python Snippets#

Sometimes, you might run into a situation where you need to express a Python construct that can't be done through an existing ScalaPy API. For this situation and to make converting Python code easier, ScalaPy provides an escape hatch via the py"" string interpolator. This lets you run arbitrary strings as Python code with the additional power of being able to interpolate in Scala values.

For example, we might want to use Python map which takes a lambda. Instead, we can use the py"" interpolator to write the expression as a piece of Python code.

import py.PyQuote
val mappedList =
py"map(lambda elem: elem + 1, ${Seq(1, 2, 3).toPythonProxy})"
// mappedList: py.Dynamic = [2, 3, 4]

If you need to run arbitrary strings of Python that are dynamically generated, you can use py.eval:

py.eval("1 + 2")
// res11: py.Dynamic = 3

Special Python Syntax#

ScalaPy includes APIs to make it possible to use Python features that require special syntax from Scala.


Python includes a "try-with-resources" feature in the form of the with keyword. In ScalaPy, you can use this feature by calling py.with with the value you want to open and a curried function using that value. For example, we can open a file with the following code:

val myFile ="../")
// myFile: py.Dynamic = <_io.TextIOWrapper name='../' mode='r' encoding='UTF-8'>
py.`with`(myFile) { file =>
// UTF-8

bracketAccess, bracketUpdate, and bracketDelete#

To index into a sequence-like Python value, py.Dynamic offers the bracketAccess, bracketUpdate, and bracketDelete APIs to load, set, or delete a value through an indexing operation. For example, we could update values of a Python list:

val pythonList =, 2, 3).toPythonProxy)
// pythonList: py.Dynamic = [1, 100, 3]
// [1, 2, 3]
// res14: py.Dynamic = 1
pythonList.bracketUpdate(1, 100)
// [1, 100, 3]

We can also delete elements of a Python dictionary:

val myDict =
// myDict: py.Dynamic = {}
myDict.bracketUpdate("hello", "world")
// {'hello': 'world'}
// {}


On supported objects, you can also delete an attribute with the attrDelete APIs:

import me.shadaj.scalapy.interpreter.CPythonInterpreter
"""class MyClass:
| myAttribute = 0""".stripMargin


Some Python APIs require you to explicitly delete a reference to a value with the del keyword. In ScalaPy, you can perform the equivalent operation by calling del on a Python value.

val myValue =
// java.lang.IllegalAccessException: The Python value you are try to access has already been released by a call to py.Any.del()
// at
// at$(Any.scala:13)
// at
// at
// at$(Any.scala:21)
// at
// at java.lang.String.valueOf(
// at

There are two key points to note when using this API. First, although the Python value is still available in Scala, any attempts to access it will result in an exception since the value has been released. Second, if there are multiple references to a single Python value from your Scala code, del will only delete a single reference and the underlying value will not be freed since other Scala code still holds a reference to it.