io.deephaven.engine.util.PythonScopeJpyImpl Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of deephaven-engine-table Show documentation
Show all versions of deephaven-engine-table Show documentation
Engine Table: Implementation and closely-coupled utilities
/**
* Copyright (c) 2016-2022 Deephaven Data Labs and Patent Pending
*/
package io.deephaven.engine.util;
import org.jpy.PyDictWrapper;
import org.jpy.PyLib;
import org.jpy.PyObject;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.stream.Stream;
public class PythonScopeJpyImpl implements PythonScope {
private final PyDictWrapper dict;
private static final ThreadLocal> threadScopeStack = new ThreadLocal<>();
private static final ThreadLocal>> threadConvertedMapStack = new ThreadLocal<>();
public static PythonScopeJpyImpl ofMainGlobals() {
return new PythonScopeJpyImpl(PyLib.getMainGlobals().asDict());
}
public PythonScopeJpyImpl(PyDictWrapper dict) {
this.dict = dict;
}
private PyDictWrapper currentScope() {
Deque scopeStack = threadScopeStack.get();
if (scopeStack == null || scopeStack.isEmpty()) {
return this.dict;
} else {
return scopeStack.peek();
}
}
@Override
public Optional getValueRaw(String name) {
// note: we *may* be returning Optional.of(None)
// None is a valid PyObject, and can be in scope
return Optional.ofNullable(currentScope().get(name));
}
@Override
public Stream getKeysRaw() {
return currentScope().keySet().stream();
}
@Override
public Stream> getEntriesRaw() {
return currentScope().entrySet().stream();
}
@Override
public boolean containsKey(String name) {
return currentScope().containsKey(name);
}
@Override
public String convertStringKey(PyObject key) {
if (!key.isString()) {
throw new IllegalArgumentException(
"Found non-string key! Expecting only string keys. " + key);
}
return key.toString();
}
@Override
public Object convertValue(PyObject value) {
if (value.isNone()) {
return value;
}
return convert(value);
}
private static Deque
© 2015 - 2024 Weber Informatics LLC | Privacy Policy