Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

.key property for ndb Model class has type of 'Key | list[Key]'

Recently moved to pyright for our type checking needs. While running pyright on a file that works with the google.cloud.Key type, I get a long list of errors saying "Argument of type 'Key | list[Key]' cannot be assigned to parameter...." for every function that accepts a parameter of Key type, with the calling code using the .key property of a ndb.Model. Example: 

 

class Foo(Model):
    some_property = model.StringProperty()

def do_something(model_key: Key) -> None:
    do_the_thing(model_key)

foo = get_foo("some_identifier")
do_something(foo.key)

 

I cannot find anything in the docs or in the SDK source to suggest that 'foo.key' here would ever be a list[Key]. However, if I look at the type stubs for this, it gives the following:

 

class ModelKey(Property):
    def __init__(self) -> None: ...
    def __get__(self, entity: Model, unused_cls: type[Model] | None = ...) -> key_module.Key | list[key_module.Key] | None: ...

 

Can anyone share any docs or knowledge around how the 'foo.key' call could ever return a list?

0 2 174
2 REPLIES 2

Did you remember to import "Key"?

 

    ......NoCommandLine ......
https://nocommandline.com
        Analytics & GUI for 
App Engine & Datastore Emulator

Yes, the types are imported and resolved correctly. I'll update the snippet just for clarity:

 

from google.cloud.ndb import Key, model

class Foo(model.Model):
    some_property = model.StringProperty()

def do_something(model_key: Key) -> None:
    do_the_thing(model_key)

foo = Foo()
foo.some_property = "something"
do_something(foo.key)

 

The specific error returned by pyright in this context is:

 

Argument of type "Key | list[Key] | None" cannot be assigned to parameter "key" of type "Key" in function "do_something"
    Type "Key | list[Key] | None" is incompatible with type "Key"
      "list[Key]" is incompatible with "Key" (reportArgumentType)"

 

Hopefully this clarifies a bit