Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

How to handle the `key' argument in PyObject_GetItem() function

I am writing a python module from a c library of my own, I need to know how to handle the PyObject_GetItem() function, specifically the key argument, the documentation is not very helpful and I have seen an example where the solution is

Py_hash_t hash;

hash = PyObject_Hash(key);

but the problem is, that I would like to be able to know whether key is a string or an integer.

I could use the PyObject_Hash() methdod if there is a way to differentitate a string key from an integer key since I can also compute the hash value corresponding to the string using the Python hash function, but i'd rather not do that because I already have a binary search implemented on the list that I am trying to be able to access via subscripting in python.

I also tried

PyArg_ParseTuple(key, "i", ...);

and for the string to check which one succeeds, but then the interpreter throws an exception because the key is not a tuple.

Upvotes: 2

Views: 380

Answers (1)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

I just found out the way to do it properly, there is a PyUnicode_Check() macro that takes a single PyObject parameter and returns 0 if the object is not a unicode object, so it returns 0 for the int key, and non-zero for the string key.

That was exactly what I needed since now I can proceed to extract the text and perform a binary search in my list.

Also, there is a PyObject_TypeCheck() function which returns the type of an object, very useful in this case too.

Upvotes: 1

Related Questions