clj-python / libpython-clj

Python bindings for Clojure
Eclipse Public License 2.0
1.08k stars 68 forks source link

cannot get key from dictionary #183

Open behrica opened 2 years ago

behrica commented 2 years ago

The below code seems to be inconsistent. Converting a Clojure map to a python dictionary shows presence of key "a". But then I can not get the key "a" out of it.

(->  {:a 1}
     py/as-python
     (py/py. keys)
     seq)
;; => ("a")

(->  {:a 1}
     py/as-python
     (py/py. get "a")
     seq)
;; => nil
cnuernber commented 2 years ago

Hmm. as-python here means the dictionary is bridged and you used a keyword argument. There is no way to pass a keyword through python and back to clojure,however, so when querying it fails. Keywords are marshalled to strings when passing back to python so keys works.

I think the issue is don't use java-specific types as keys when using bridged dictionaries. I don't see a great way around this.

behrica commented 2 years ago

Maybe writing the code like this, shows the issue better:

(def py-dict (py/as-python {:a 1}))
(seq (py/py. py-dict keys))
-> ("a")
(py/py. py-dict get "a")
->nil

I am able to create a "dictionary", which

This seems to break the contract of a dictionary.

and exactly the same code, does work, if I give a string initially:

(def py-dict (py/as-python {"a" 1}))
(seq (py/py. py-dict keys))
-> ("a")
(py/py. py-dict get "a")
->1

In my view, the object created by (py/as-python {:a 1}) is invalid, as it does not behave like a dictionary should behave. (so maybe the as-python call should fail getting keywords)

behrica commented 2 years ago

The created python object behaves very strange...

(def py-dict (py/as-python {:a 1}))
(seq (py/py. py-dict items))
(('a', None))    ;; value of "a" is None ....
(seq (py/py. py-dict values))    
(1)     ;; list of values is: (1)

I am not expecting to get a python-object having a "keyword", as keyword are not supported in python. But it seems that I do not get a dictionar of:

dict(a=1)

neither.

cnuernber commented 2 years ago

That is a good point and definitely one issue here.