Skip to content

Latest commit

 

History

History
executable file
·
48 lines (35 loc) · 1.86 KB

getting-started.md

File metadata and controls

executable file
·
48 lines (35 loc) · 1.86 KB
slug id title sidebar_label
/
getting-started
Getting Started with ScalaPy
Getting Started

ScalaPy makes it easy to use Python libraries from Scala code. With a simple API, automatic conversion between Scala and Python types, and optional static typing, ScalaPy scales from hobby projects to production systems.

Installation

First, add ScalaPy to your SBT build:

libraryDependencies += "me.shadaj" %% "scalapy-core" % "0.4.0"

You'll then need to add the Python native libraries to your project and configure SBT to run your code in a separate JVM instance.

fork := true

import scala.sys.process._
javaOptions += s"-Djava.library.path=${"python3-config --ldflags".!! + "/lib"}"

If you'd like to use Scala Native, follow the instructions there to create a project with Scala Native 0.4.0-M2. Then, add the following additional configuration to your SBT build to link the Python interpreter.

import scala.sys.proces._
nativeLinkingOptions ++= "python3-config --ldflags".!!.split(' ').map(_.trim).filter(_.nonEmpty).toSeq

Hello World!

Now that ScalaPy is installed, let's start with a simple example. ScalaPy offers a dynamically typed API that's great for making quick Python calls with little ceremony. First, we can use the Python len function to calculate the length of a list. Using py.Dynamic.global, you can access any members of the global scope.

import me.shadaj.scalapy.py
import me.shadaj.scalapy.py.SeqConverters

val listLengthPython = py.Dynamic.global.len(List(1, 2, 3).toPythonProxy)

Here, we took a Scala List, converted it to a Python list, sent it to the len function, and got back a Python number.

To convert Python values back into Scala, we use the .as method and pass in the type we want.

val listLength = listLengthPython.as[Int]