oracle / oracle/graalpython

Special methods (__foo__) don't work as expected on ProxyObject methods

Open
#249 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
1.6k
Forks
155
Avg merge
9h 42m
Merged PRs (30d)
36

Description

Considering Python's duck-typing semantics, it'd be really useful if it were possible to define custom 'special functions' (like __add__, __str__, etc) on ProxyObject, in order to build custom objects that mesh nicely with the rest of Python.

Defining these methods is currently possible, but Python doesn't pick them up properly. For instance, consider the following code (pardon the Clojure ;)):

(import '[org.graalvm.polyglot Context] '[org.graalvm.polyglot.proxy ProxyObject ProxyExecutable])
(let [ctx (Context/create (into-array String ["python"]))
      obj (ProxyObject/fromMap {"__len__" (reify ProxyExecutable (execute [_ _] 1))
                                "__add__" (reify ProxyExecutable (execute [_ _] 2))
                                "__str__" (reify ProxyExecutable (execute [_ _] "hi"))})]
  (.putMember (.getBindings ctx "python") "x" obj)
  (.eval ctx "python" "print(x.__len__(), x.__add__(1), x.__str__())")
  (.eval ctx "python" "print(x)")
  (try (.eval ctx "python" "print(len(x))") (catch Exception e (println (ex-message e))))
  (try (.eval ctx "python" "print(x + 1)") (catch Exception e (println (ex-message e)))))

The expected output here should be

1 2 hi
hi
1
2

but in reality, what we get is:

1 2 hi
<foreign object at 0x67b613f9>
AttributeError: foreign object has no attribute '__len__'
TypeError: unsupported operand type(s) for +: 'foreign' and 'int'

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the example using Context/create, ProxyObject/fromMap, and the Python eval calls. Trace how ProxyObject members are exposed to Python's special-method lookup, then verify that str, len, and add work through print(), len(), and + with the expected output.

Written by the indexing model from the issue text.

Assessment

Tech stack
java, python
Domain
api, backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.