lupa
lupa copied to clipboard
Object key existence check not consistent with lua
I have a Lua function that receives a python dict-based object 'attributes' (from sqlachemy) as argument and want to check for presence of a key - as per python hasattr(obj, 'some_key').
In Lua I would use:
if attribues['somekey'] ~= nil then
-- key exists ...
but lupa raises a KeyError or AttibuteError exceptions - also using python.as_itemgetter or pyhton.as_attrgetter.
This forces me to use pcall to handle the exception:
if pcall( function( attr, key ) return attr[key] end, attributes, 'cost') then
print( "cost found")
else
print( "cost not found")
end
Is there a more convenient method for lupa to test key existence? It feels like there should be - perhaps I missed something. Reason for the qu is that the lua code is exposed to and editable by end users of an app - which will be a cause for confusion.
Did you manage to find a workaround? I'm having the same problem.
As per the original post, the starting point is a python object. My solution was to implement has_attr in the object's python model:
Case sensitive:
def has_attr(self, attr):
return attr in self.attributes
Case insensitive:
def has_attr(self, attr):
lattr = attr.lower()
for key in self.attributes:
if key.lower() == lattr:
return True
return False
with that in place I can now call has_attr on the object from Lua:
if myObj.has_attr('some_key') then
- key exists ...