Which python static checker can catch forgotten await problems?

2024/9/23 8:06:19

Code:

from typing import AsyncIterableimport asyncioasync def agen() -> AsyncIterable[str]:print('agen start')yield '1'yield '2'async def agenmaker() -> AsyncIterable[str]:print('agenmaker start')return agen()async def amain():print('amain')async for item in agen():passasync for item in await agenmaker():pass# Error:async for item in agenmaker():passdef main():asyncio.get_event_loop().run_until_complete(amain())if __name__ == '__main__':main()

As you can see, it is type-annotated, and contains an easy-to-miss error.

However, neither pylint nor mypy find that error.

Aside from unit tests, what options are there for catching such errors?

Answer

MyPy is perfectly capable of finding this issue. The problem is that unannotated functions are not inspected. Annotate the offending function as -> None and it is correctly inspected and rejected.

# annotated with return type
async def amain() -> None:print('amain')async for item in agen():passasync for item in await agenmaker():pass# Error:async for item in agenmaker(): # error: "Coroutine[Any, Any, AsyncIterable[str]]" has no attribute "__aiter__" (not async iterable)pass

If you want to eliminate such issues slipping through, use the flags --disallow-untyped-defs or --check-untyped-defs.


MyPy: Function signatures and dynamic vs static typing

A function without type annotations is considered to be dynamically typed by mypy:

def greeting(name):return 'Hello ' + name

By default, mypy will not type check dynamically typed functions. This means that with a few exceptions, mypy will not report any errors with regular unannotated Python.

https://en.xdnf.cn/q/71791.html

Related Q&A

Tkinter : Syntax highlighting for Text widget

Can anyone explain how to add syntax highlighting to a Tkinter Text widget ?Every time the program finds a matching word, it would color that word to how I want. Such as : Color the word tkinter in pi…

how to use pkgutils.get_data with csv.reader in python?

I have a python module that has a variety of data files, (a set of csv files representing curves) that need to be loaded at runtime. The csv module works very well # curvefile = "ntc.10k.csv"…

How to make celery retry using the same worker?

Im just starting out with celery in a Django project, and am kinda stuck at this particular problem: Basically, I need to distribute a long-running task to different workers. The task is actually broke…

Make an AJAX call to pass drop down value to the python script

I want to pass the selected value from dropdown which contains names of databases and pass it to the python script in the background which connects to the passed database name. Following is the ajax co…

PyLint 1.0.0 with PyDev + Eclipse: include-ids option no longer allowed, breaks Eclipse integration

As noted in this question: How do I get Pylint message IDs to show up after pylint-1.0.0?pylint 1.0.0 no longer accepts "include-ids" option. (It returns "lint.py: error: no such optio…

Shifting all rows in dask dataframe

In Pandas, there is a method DataFrame.shift(n) which shifts the contents of an array by n rows, relative to the index, similarly to np.roll(a, n). I cant seem to find a way to get a similar behaviour …

Pandas dataframe: omit weekends and days near holidays

I have a Pandas dataframe with a DataTimeIndex and some other columns, similar to this:import pandas as pd import numpy as nprange = pd.date_range(2017-12-01, 2018-01-05, freq=6H) df = pd.DataFrame(ind…

How to dump a boolean matrix in numpy?

I have a graph represented as a numpy boolean array (G.adj.dtype == bool). This is homework in writing my own graph library, so I cant use networkx. I want to dump it to a file so that I can fiddle wit…

Cant append_entry FieldList in Flask-wtf more than once

I have a form with flask-wtf for uploading images, also file field can be multiple fields. my form: class ComposeForm(Form):attachment = FieldList(FileField(_(file)), _(attachment))add_upload = SubmitF…

What is the best way to use python code from Scala (or Java)? [duplicate]

This question already has answers here:Closed 11 years ago.Possible Duplicate:Java Python Integration There is some code written in Python and I need to use it from Scala. The code uses some native C.…