Python 怎么声明变量比较优雅
資深大佬 : just1 3
问题是这样:我需要一个全局变量,但是在之后的 async function 里面才会对其进行赋值,这是我几个尝试,但是 pycharm 多少都会报 Warning
先声明为 None
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'
先声明为 None,用 type hint 标记
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 需要在其他函数内使用
大佬有話說 (9)