I have a situation where I need to enable certain features if and only if some other application is deployed (in k8s cluster) alongside my application.
We describe this to the running application container using environment variables. This leads to some code like this:
ADVANCED_FEATURES_ENABLED = os.env.get(["ADVANCED_FEATURES_ENABLED"], False) # I know this won't parse a bool correctly, but it still illustrates the use case.
class MyModel(pydantic.BaseModel):
field: str
if ADVANCED_FEATURES_ENABLED: # This is the line in question here
advanced_field: str
This works just fine as python code, but static analysis tools like mypy and pylint do not actually execute python code. So, (not unexpectedly) some later code that tries to access instance_of_my_model.advanced_field
will have type errors.
I did notice that if we were to define the condition as if True:
or if False:
, mypy would be able to handle it correctly, but even if I use ADVANCED_FEATURES_ENABLED = True
and then if ADVANCED_FEATURES_ENABLED:
mypy will not recognized advanced_field
as a member of MyModel
.
So the question: Is there some way I can configure mypy to recognize the above line as True or False?
I’ve tried a number of variations on the source code above, and I can get mypy to accept either the “basic” or the “advanced” definition of the class, but not “both”. It’s clear to me I need something “above” the code itself, at the mypy configuration level, but I haven’t had much luck with searching.
I’m hoping that, since there is a very limited number of expressions I want mypy to understand, there may be some kind of configuration where I can do something like: mypy . --expression "ADVANCED_FEATURES_ENABLED=True"
or mypy . --expression "ADVANCED_FEATURES_ENABLED=False"
Then I could run mypy against both “configurations” of my application. Bonus points if there is a way to get pylint to do this as well, but my focus is on mypy atm.