GvRs App Engine ndb Library as well as monocle and - to my understanding - modern Javascript use Generators to make async code look like blocking code.
Things are decorated with @ndb.tasklet
. They yield
when they want to give back execution to the runloop and when they have their result ready they raise StopIteration(value)
(or the alias ndb.Return
):
@ndb.tasklet
def get_google_async():
context = ndb.get_context()
result = yield context.urlfetch("http://www.google.com/")
if result.status_code == 200:
raise ndb.Return(result.content)
raise RuntimeError
To use such a Function you get a ndb.Future
object back and call the get get_result()
Function on that to wait for the result and get it. E.g.:
def get_google():
future = get_google_async()
# do something else in real code here
return future.get_result()
This all works very nice. but how to add type Annotations? The correct types are:
So far, I came only up with cast
ing the async function.
def get_google():
# type: () -> str
future = get_google_async()
# do something else in real code here
return cast('str', future.get_result())
Unfortunately this is not only about urlfetch
but about hundreds of Methods- mainly of ndb.Model.
Annotations enable you to modify the names of the elements in your typed DataSet without modifying the underlying schema. Modifying the names of the elements in your underlying schema would cause the typed DataSet to refer to objects that do not exist in the data source, as well as lose a reference to the objects that do exist in the data source.
To use typed DataSet annotations, you must include the following xmlns reference in your XML Schema definition language (XSD) schema. To create an xsd from database tables, see WriteXmlSchema or Working with Datasets in Visual Studio.
Python’s Type Annotations Type annotations in Python are not make-or-break like in our C example. They’re optional chunks of syntax that we can add to make our code more explicit. Erroneous type annotations will do nothing more than highlight the incorrect annotation in our code editor — no errors are ever raised due to annotations.
What is Type Annotation in TypeScript TypeScript uses type annotations to explicitly specify types for identifiers such variables, functions, objects, etc. TypeScript uses the syntax : type after an identifier as the type annotation, where type can be any valid type. Once an identifier is annotated with a type, it can be used as that type only.
get_google_async
itself is a generator function, so type hints can be () -> Generator[ndb.Future, None, None]
, I think.
As for get_google
, if you don't want to cast, type checking may work.
like
def get_google():
# type: () -> Optional[str]
future = get_google_async()
# do something else in real code here
res = future.get_result()
if isinstance(res, str):
return res
# somehow convert res to str, or
return None
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With