Permalink
Browse files

Add Python methods to hashtable so it can be used like a dict (#5620)

  • Loading branch information...
geographika authored and rouault committed Aug 16, 2018
1 parent f838ab1 commit c59ab11ca6cf410a8b2bcc71a9fb871a27754efa
Showing with 54 additions and 45 deletions.
  1. +33 −35 mapscript/python/pymodule.i
  2. +21 −10 mapscript/python/tests/cases/hashtest.py
@@ -93,45 +93,43 @@ CreateTupleFromDoubleArray( double *first, unsigned int size ) {
$result = t_output_helper($result,r);
}
/*
* Typemap hashTableObj* -> dict
*/
%typemap(out) hashTableObj*
{
/* %typemap(out) hashTableObj* */
const char* key;
hashTableObj *hashTable = $1;
$result = PyDict_New();
key = msFirstKeyFromHashTable(hashTable);
while( key )
{
const char* val = msLookupHashTable(hashTable, key);
if( val )
{
%#if PY_VERSION_HEX >= 0x03000000
PyObject *py_key = PyUnicode_FromString(key);
PyObject *py_val = PyUnicode_FromString(val);
%#else
PyObject *py_key = PyString_FromString(key);
PyObject *py_val = PyString_FromString(val);
%#endif
PyDict_SetItem($result, py_key, py_val );
Py_DECREF(py_key);
Py_DECREF(py_val);
}
key = msNextKeyFromHashTable(hashTable, key);
}
}
* Add dict methods to the hashTableObj object
*/
%extend hashTableObj{
%pythoncode %{
%typemap(freearg) hashTableObj*
{
/* %typemap(freearg) hashTableObj* */
msFreeHashTable( $1 );
}
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, value):
return self.set(key, value)
def __delitem__(self, key) :
return self.remove(key)
def __contains__(self, key):
return key.lower() in [k.lower() for k in self.keys()]
def __len__(self):
return self.numitems
def keys(self):
keys = []
k = None
while True :
k = self.nextKey(k)
if k :
keys.append(k)
else :
break
return keys
%}
};
/**************************************************************************
* MapServer Errors and Python Exceptions
@@ -85,17 +85,28 @@ def testNextKey(self):
key = self.table.nextKey(key)
assert key == None, key
# TODO
# def testKeys(self):
# "get sequence of keys"
# keys = self.table.keys()
# assert keys == self.keys, keys
#
# def testValues(self):
# "get sequence of values"
# values = self.table.values()
# assert values == self.values, values
# tests using the Python dictionary access methods
def testDictKeys(self):
assert sorted(self.keys) == sorted(self.table.keys())
def testDictItems(self):
assert len(self.keys) == len(self.table)
def testCheckDictContains(self):
for key in self.keys:
assert key in self.table.keys()
def testGetDictValue(self):
for key, value in zip(self.keys, self.values):
assert self.table[key] == value
assert self.table[key.upper()] == value
assert self.table[key.capitalize()] == value
def testRemoveDictItem(self):
key = self.keys[0]
del self.table[key]
assert self.table[key] == None
# ===========================================================================
# Test begins now

0 comments on commit c59ab11

Please sign in to comment.