Skip to content

Commit

Permalink
Initialize Python code only once
Browse files Browse the repository at this point in the history
  • Loading branch information
kiendang committed Aug 5, 2021
1 parent 20b9394 commit bf7c893
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 23 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import json


def format_display_data(obj, include):
repr_methods = ((t, m) for m, t in include if m in set(dir(obj)))
representations = ((t, getattr(obj, m)()) for t, m in repr_methods)

display_data = (
(t, (r[0], r[1]) if isinstance(r, tuple) and len(r) == 2 else (r, None))
for t, r in representations if r is not None
)
display_data = [(t, m, md) for t, (m, md) in display_data if m is not None]

data = [
(t, d if isinstance(d, str) else json.dumps(d))
for t, d, _ in display_data
]
metadata = [
(t, md if isinstance(md, str) else json.dumps(md))
for t, _, md in display_data if md is not None
]

return data, metadata
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@ import jupyter.{Displayer, Displayers}
import me.shadaj.scalapy.interpreter.CPythonInterpreter
import me.shadaj.scalapy.py
import me.shadaj.scalapy.py.{PyQuote, SeqConverters}
import scala.io.Source
import scala.jdk.CollectionConverters._

package object scalapy {
CPythonInterpreter.execManyLines(Source.fromResource("format_display_data.py").mkString)

def initDisplay: Unit = {
Displayers.register(
classOf[py.Any],
Expand All @@ -21,8 +24,6 @@ package object scalapy {
}

private def formatDisplayData(obj: py.Any): (Map[String, String], Map[String, String]) = {
CPythonInterpreter.execManyLines(formatDisplayDataPy)

val displayData = py.Dynamic.global.format_display_data(obj, allReprMethods.toPythonCopy)
val data = displayData.bracketAccess(0).as[List[(String, String)]].toMap
val metadata = displayData.bracketAccess(1).as[List[(String, String)]].toMap
Expand All @@ -42,25 +43,4 @@ package object scalapy {

private lazy val allReprMethods: Seq[(String, String)] =
mimetypes.map { case (k, v) => s"_repr_${k}_" -> v }.toSeq

private val formatDisplayDataPy: String =
"""import json
|def format_display_data(obj, include):
| repr_methods = ((t, m) for m, t in include if m in set(dir(obj)))
| representations = ((t, getattr(obj, m)()) for t, m in repr_methods)
| display_data = (
| (t, (r[0], r[1]) if isinstance(r, tuple) and len(r) == 2 else (r, None))
| for t, r in representations if r is not None
| )
| display_data = [(t, m, md) for t, (m, md) in display_data if m is not None]
| data = [
| (t, d if isinstance(d, str) else json.dumps(d))
| for t, d, _ in display_data
| ]
| metadata = [
| (t, md if isinstance(md, str) else json.dumps(md))
| for t, _, md in display_data if md is not None
| ]
| return data, metadata
""".stripMargin
}

0 comments on commit bf7c893

Please sign in to comment.