Hey folks,
so I’ve seen a couple of threads with similar questions, but none quite answer the situation I am in.
First off, why I did things the way I did.
I have a global variable called HELPER, that I initially wanted to set like so:
#script2.py
HELPER = _HelperClass()
...
def run() -> None:
...
However, the _HelperClass is dependent on a config file, whose location is evaluated at runtime in another script:
#script1.py
import script2
...
Config.set_env(...)
...
As you can see, script2 is being imported before the the environment for the Config is set, and thus HELPER throws an error because _HelperClass() cannot determine the location of the Config file.
To ‘lazy load’ HELPER I handled it like so:
#script2.py
HELPER = None
def _initialize() -> None:
global HELPER
HELPER = _HelperClass()
...
def run() -> None:
_initialize()
...
This works really well, except for one thing: mypy.
Since HELPER is only technically of type Optional[_HelperClass], I feel that it doesn’t make sense to unwrap the Optional each time it is used.
On each line I use HELPER though, mypy complains that
"error: Item 'None' of Optional[_HelperClass] has no attribute 'my_attribute' [union-attr]"
since HELPER is seen as an Optional. I really don’t like the idea of checking
if HELPER is not None:
...
everytime HELPER is called, just to satisfy mypy.
I was wondering whether any of you have come across something similar or I’d just love to hear your input on how you would solve this situation in the most pythonic way, as I am still quite new to the language and programming as a whole!
P.S: I have come across this PEP before and it seems like this would be exactly what I need. Sadly though, it is not implemented yet.
Thank you guys in advance!