简体   繁体   中英

Declare a global variable with certain type

In python, is it possible to declare a global variable with a type? 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. 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).

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. You don't need to do it like this, but if you don't initialize here, flake8 will complain. There are a few other ways to do this, but this one works and satisfies my linters (flake8, pylint, mypy).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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