推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
just1
V2EX  ›  Python

Python 怎么声明变量比较优雅

  •  
  •   just1 · Sep 3, 2020 · 3470 views
    This topic created in 2265 days ago, the information mentioned may be changed or developed.

    问题是这样:我需要一个全局变量,但是在之后的 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 replies  •  2020-09-03 18:48:14 +08:00
    BBCCBB
    BBCCBB
    Sep 3, 2020
    1
    试试 typing.Union[asyncpg.pool.Pool, None] ?
    just1
    just1
    OP
    Sep 3, 2020
    2
    @BBCCBB #1 一样会有 Cannot find reference 'xxx' in 'None',应该是因为我直接赋值为 None 的原因
    013231
    013231
    Sep 3, 2020
    3
    type hint,
    013231
    013231
    Sep 3, 2020
    4
    conn_pool: asyncpg.pool.Pool = None
    改为
    013231
    013231
    Sep 3, 2020
    5
    conn_pool: asyncpg.pool.Pool
    去掉" = None"即可
    just1
    just1
    OP
    Sep 3, 2020
    6
    @013231 #5 喔,这个应该是最优解了,之前我搜索 define variable without value 没找到这个方式,谢谢
    HFcbyqP0iVO5KM05
    HFcbyqP0iVO5KM05
    Sep 3, 2020 via Android
    7
    conn_pool: asyncpg.pool.Pool = None # noqa
    laike9m
    laike9m
    Sep 3, 2020❤️1
    8
    首先,PyCharm 的警告都是可以关的,而且控制粒度比较细,你要是不爽关了对应的警告就行了

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

    @laike9m #8 关了是最后的退路~
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2456 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 11:34 · PVG 19:34 · LAX 03:34 · JFK 06:34
    ♥ Do have faith in what you're doing.