Python 怎么声明变量比较优雅

2020-09-03 18:21:27 +08:00
 just1

问题是这样:我需要一个全局变量,但是在之后的 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 需要在其他函数内使用

2404 次点击
所在节点    Python
9 条回复
BBCCBB
2020-09-03 18:25:58 +08:00
试试 typing.Union[asyncpg.pool.Pool, None] ?
just1
2020-09-03 18:27:17 +08:00
@BBCCBB #1 一样会有 Cannot find reference 'xxx' in 'None',应该是因为我直接赋值为 None 的原因
013231
2020-09-03 18:27:18 +08:00
type hint,
013231
2020-09-03 18:27:25 +08:00
conn_pool: asyncpg.pool.Pool = None
改为
013231
2020-09-03 18:27:46 +08:00
conn_pool: asyncpg.pool.Pool
去掉" = None"即可
just1
2020-09-03 18:30:30 +08:00
@013231 #5 喔,这个应该是最优解了,之前我搜索 define variable without value 没找到这个方式,谢谢
gulu
2020-09-03 18:30:34 +08:00
conn_pool: asyncpg.pool.Pool = None # noqa
laike9m
2020-09-03 18:37:59 +08:00
首先,PyCharm 的警告都是可以关的,而且控制粒度比较细,你要是不爽关了对应的警告就行了

其次,这种情况一般用 typing.Optional 就可以解决:
https://docs.python.org/3/library/typing.html#typing.Optional
just1
2020-09-03 18:48:14 +08:00
@gulu #7
@laike9m #8
按照#5 的方案就可以解决了 conn_pool: asyncpg.pool.Pool,不需要附值

@laike9m #8 关了是最后的退路~

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/703978

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX