简体   繁体   English

声明一个特定类型的全局变量

[英]Declare a global variable with certain type

In python, is it possible to declare a global variable with a type? python中,是否可以声明一个带类型的全局变量? I know this is fine to declare a local variable like this.我知道这样声明局部变量很好。

student: Student

Or或者

global student

But I'm looking for something like this但我正在寻找这样的东西

global student: Student

python变量没有设置类型,因此您只需要声明全局变量-它将自动是在函数范围之外声明的任何变量。

I did it like this:我是这样做的:

from typing import Union
from my_class import MyClass

foo_my_class: Union[MyClass, None] = None

def setup_function():
    """ test setup """
    global foo_my_class
    foo_my_class = MyClass()
...

Ie, this is a test module, and I want foo_my_class to be available at global scope for every test in the module.即,这是一个测试模块,我希望foo_my_class在全局 scope 上对模块中的每个测试可用。 The setup_function() runs before every test, so I re-initialize foo_my_class each time (so that it is fresh and clean for each test). setup_function()在每次测试之前运行,所以我每次都重新初始化foo_my_class (以便每次测试都是新鲜干净的)。

foo_my_class still has to be declared at global scope, and it makes most sense to me to init to None, hence the Union typing. foo_my_class仍然必须在全局 scope 处声明,对我来说初始化为 None 最有意义,因此使用 Union 类型。 You don't need to do it like this, but if you don't initialize here, flake8 will complain.不需要这样做,但如果你不在这里初始化,flake8 会报错。 There are a few other ways to do this, but this one works and satisfies my linters (flake8, pylint, mypy).还有一些其他方法可以做到这一点,但这个方法有效并满足我的 linters(flake8、pylint、mypy)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM