Search code examples
pythonamazon-dynamodbboto3

how to check if a dynamodb attribute is a reserved keyword (in Python)


I need to update a dynamodb table using the update_item method. I get a dynamic list of attribute to update, so some of them can be reserved words.

Is there a way to check (in Python) if an attribute is a reserved word?

There is a list of all ~570 words here. So in theory I can create a static list and check it, but I want to believe there is a better way.

Example to clarify:

cols_to_update = ["a", "comment"] -- comment is a dynamodb reserved word

My code will generate the following:

update_expression = "SET a = :_a, comment = :_comment"
expression_attribute_values = {":_a": some_value, ":_comment": some_value}

and use it in the update command:

table.update_item(
  Key={
    'id': some_id
  },
  UpdateExpression=update_expression,
  ExpressionAttributeValues=expression_attribute_values
)

this will throw an error saying the comment is a reserved word: botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the UpdateItem operation: Invalid UpdateExpression: Attribute name is a reserved keyword; reserved keyword: comment

I can use ExpressionAttributeNames :

table.update_item(
  Key={
    'id': some_id
  },
  UpdateExpression=update_expression,
  ExpressionAttributeValues=expression_attribute_values,
  ExpressionAttributeNames={
    "#c": "comment"
  }
)

but I don't know which of the attributes I update are reserved words and need to be in the ExpressionAttributeNames


Solution

  • Always use expressionAttributeValues/Names so that you do not have to check if the word is reserved or not. That is not a static list of reserved words and can be changed at anytime. There is no API to check for reserved key words.