Python – ndb. How is StringProperty equal to a python string?

ndb. How is StringProperty equal to a python string?… here is a solution to the problem.

ndb. How is StringProperty equal to a python string?

I have this ndb model class

class foo(ndb. Model):
  abc = ndb. StringProperty()

Now when I use abc like this:

if foo.abc == "a":
  print "I'm in!"

It goes into the if block and prints I'm in!

How is this possible?

I’ve also tried printing foo.abc, which returns StringProperty('abc').

Solution

You must instantiate an instance of the class to use the property correctly.

class Foo(ndb. Model):
  abc = ndb. StringProperty()

foo = Foo()
foo.abc = 'some val'
print foo.abc  # prints 'some val'
print foo.abc == 'a' # prints False
print Foo.abc == 'a' # prints something not boolean - can't check now.

You’re getting "I'm in!" because the ndb attribute is overriding the __equal__ operator and returning a non-null object that is considered true<. This is used to make queries like query.filter(foo.abc == 'def').

Related Problems and Solutions