All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.xiaopy.python.PyMap Maven / Gradle / Ivy

There is a newer version: 12.1.13
Show newest version
package com.xiaopy.python;

import java.util.*;
import org.jetbrains.annotations.*;


class PyMap extends AbstractMap {
    private final PyObject obj;
    private final MethodCache methods;

    public PyMap(PyObject obj) {
        this.obj = obj;
        methods = new MethodCache(obj);
        methods.get("__contains__");
        methods.get("__getitem__");
        methods.get("__iter__");
        methods.get("__len__");
    }

    @Override public @NotNull Set> entrySet() {
        return new AbstractSet>() {
            @Override public int size() {
                return methods.get("__len__").call().toInt();
            }

            @Override public @NotNull Iterator> iterator() {
                return new PyIterator>(methods) {
                    @Override protected Entry makeNext(final PyObject key) {
                        return new Entry() {
                            @Override public PyObject getKey() { return key; }
                            @Override public PyObject getValue() { return get(key); }
                            @Override public PyObject setValue(PyObject value) {
                                return put(key, value);
                            }
                        };
                    }
                };
            }

            @Override public void clear() {
                methods.get("clear").call();
            }
        };
    }


    // === Read methods ======================================================

    @Override public boolean containsKey(Object key) {
        return methods.get("__contains__").call(key).toBoolean();
    }

    @Override public PyObject get(Object key) {
        // For consistency with PyList, use `__getitem__` rather than `get`. Unlike PyList, the
        // Python interface accepts the same parameters as the Java one, so we can allow Python
        // to do the validation.
        try {
            return methods.get("__getitem__").call(key);
        } catch (PyException e) {
            if (e.getMessage().startsWith("KeyError:")) {
                return null;
            } else {
                throw e;
            }
        }
    }


    // === Modification methods ==============================================
    //
    // See note in PyList.

    @Override public PyObject put(PyObject key, PyObject value) {
        PyObject oldElement = get(key);
        methods.get("__setitem__").call(key, value);
        return oldElement;
    }

    @Override public PyObject remove(Object key) {
        return methods.get("pop").call(key, null);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy