跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • Python 怎么声明变量比较优雅
未分類
3 9 月 2020

Python 怎么声明变量比较优雅

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)

  • 資深大佬 : BBCCBB

    试试 typing.Union[asyncpg.pool.Pool, None] ?

  • 主 資深大佬 : just1

    @BBCCBB #1 一样会有 Cannot find reference ‘xxx’ in ‘None’,应该是因为我直接赋值为 None 的原因

  • 資深大佬 : 013231

    type hint,

  • 資深大佬 : 013231

    conn_pool: asyncpg.pool.Pool = None
    改为

  • 資深大佬 : 013231

    conn_pool: asyncpg.pool.Pool
    去掉” = None”即可

  • 主 資深大佬 : just1

    @013231 #5 喔,这个应该是最优解了,之前我搜索 define variable without value 没找到这个方式,谢谢

  • 資深大佬 : gulu

    conn_pool: asyncpg.pool.Pool = None # noqa

  • 資深大佬 : laike9m

    首先,PyCharm 的警告都是可以关的,而且控制粒度比较细,你要是不爽关了对应的警告就行了

    其次,这种情况一般用 typing.Optional 就可以解决:
    https://docs.python.org/3/library/typing.html#typing.Optional

  • 主 資深大佬 : just1

    @gulu #7
    @laike9m #8
    按照#5 的方案就可以解决了 conn_pool: asyncpg.pool.Pool,不需要附值

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

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具