Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 498
Yufeng Avatar asked Apr 12 '26 06:04

Yufeng


1 Answers

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()
...

I.e., 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).

like image 163
Hawkeye Parker Avatar answered Apr 13 '26 18:04

Hawkeye Parker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!