libpython-clj icon indicating copy to clipboard operation
libpython-clj copied to clipboard

cannot get key from dictionary

Open behrica opened this issue 4 years ago • 4 comments

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

behrica avatar Nov 13 '21 10:11 behrica

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.

cnuernber avatar Dec 13 '21 14:12 cnuernber

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

  • seems to have a key "a" (as told by keys function)
  • but asking it for "a" does not work

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 avatar Dec 13 '21 20:12 behrica

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.

behrica avatar Dec 13 '21 20:12 behrica

That is a good point and definitely one issue here.

cnuernber avatar Dec 15 '21 13:12 cnuernber