Andrei-Marius Longhin Andrei-Marius Longhin - 10 months ago 25
Python Question

Iterate through StringProperty

I'm trying to get the value (as a string) of a StringProperty but without success.
I need to iterate through it and it raises an error if I just try and iterate through the property, since it's not an iterable.
How could I convert a StringProperty to a Python string, or to something that I can iterate through and that has a len?


This is how I declare the Kind that has the problem:

class Game(ndb.Model):
"""Game object"""
target = ndb.StringProperty(required=True)
attempts_allowed = ndb.IntegerProperty(required=True)
attempts_remaining = ndb.IntegerProperty(required=True, default=5)
game_over = ndb.BooleanProperty(required=True, default=False)
user = ndb.KeyProperty(required=True, kind='User')
users_word = ndb.StringProperty(required=True)

The last property is the one I need to iterate through. And this is the function which raises an error:

def update_users_word(self, letter):
word_as_list = list(self.users_word)
print ("String is: " + str(getattr(self, 'users_word')))

for pos in self.find_letter_positions_in_word(letter,
word_as_list[pos] = letter

self.users_word = ''.join(word_as_list)

and this is the exact error:

Number/", line 59, in update_users_word
word_as_list = list(self.users_word)
TypeError: 'StringProperty' object is not iterable

Hope this is more clear now


You have declared this as a classmethod. That means that self is not an instance of Game, but the class itself. So self.user_word refers to the property that is defined on the class, not the string that would be available via the instance.

Use a normal @property decorator instead, or just leave it as a standard method.