问题是这样:我需要一个全局变量,但是在之后的 async function 里面才会对其进行赋值,这是我几个尝试,但是 pycharm 多少都会报 Warning
app = FastAPI()
conn_pool = None
@app.on_event("startup")
async def startup():
global conn_pool
conn_pool = await asyncpg.create_pool()
@app.get('/')
async def index():
async with conn_pool.acquire() as conn:
pass # do something
这样底下的所有 conn_pool 的操作都会报Cannot find reference 'xxx' in 'None'
app = FastAPI()
conn_pool: asyncpg.pool.Pool = None
@app.on_event("startup")
async def startup():
global conn_pool
conn_pool = await asyncpg.create_pool()
@app.get('/')
async def index():
async with conn_pool.acquire() as conn:
pass # do something
这样在conn_pool: asyncpg.pool.Pool = None
这一行会报Expected type 'Pool', got 'None' instead
app = FastAPI()
@app.on_event("startup")
async def startup():
global conn_pool
conn_pool = await asyncpg.create_pool()
@app.get('/')
async def index():
async with conn_pool.acquire() as conn:
pass # do something
可以用,但是在global conn_pool
会报Global variable 'conn_pool' is undefined at the module level
虽然所有代码都可以运行,但是都会错误提示,感觉很不舒服。求助有没有完美的解决方案。
我这里需要全局变量的原因是 conn_pool 需要在其他函数内使用
1
BBCCBB 2020-09-03 18:25:58 +08:00
试试 typing.Union[asyncpg.pool.Pool, None] ?
|
2
just1 OP @BBCCBB #1 一样会有 Cannot find reference 'xxx' in 'None',应该是因为我直接赋值为 None 的原因
|
3
013231 2020-09-03 18:27:18 +08:00
type hint,
|
4
013231 2020-09-03 18:27:25 +08:00
conn_pool: asyncpg.pool.Pool = None
改为 |
5
013231 2020-09-03 18:27:46 +08:00
conn_pool: asyncpg.pool.Pool
去掉" = None"即可 |
6
just1 OP @013231 #5 喔,这个应该是最优解了,之前我搜索 define variable without value 没找到这个方式,谢谢
|
7
HFcbyqP0iVO5KM05 2020-09-03 18:30:34 +08:00 via Android
conn_pool: asyncpg.pool.Pool = None # noqa
|
8
laike9m 2020-09-03 18:37:59 +08:00 1
首先,PyCharm 的警告都是可以关的,而且控制粒度比较细,你要是不爽关了对应的警告就行了
其次,这种情况一般用 typing.Optional 就可以解决: https://docs.python.org/3/library/typing.html#typing.Optional |