I’m going through the FastAPI documentation tutorial and there’s a section where I create an enum for a path parameter (Path Parameters - FastAPI). My code ends up looking like this when I copy and paste it from the page:
from enum import Enum
from fastapi import FastAPI
class ModelName(str, Enum):
alexnet = "alexnet"
resnet = "resnet"
lenet = "lenet"
app = FastAPI()
@app.get("/models/{model_name}")
async def get_model(model_name: ModelName):
if model_name == ModelName.alexnet:
return {"model_name": model_name, "message": "Deep Learning FTW!"}
if model_name.value == "lenet":
return {"model_name": model_name, "message": "LeCNN all the images"}
return {"model_name": model_name, "message": "Have some residuals"}
I’m a bit new to Python still, especially trying to understand how type hints work. Coming from other programming languages, a few of which are compiled, I was expecting to be able to get type hinting hints in my code editor (VS Code in this case) if I accidentally tried to assign the wrong type to an enum value. And I expected my code editor to be able to warn me about this using a linter or some other static code analysis tool, so that I wouldn’t have to run the code to get an error.
For example, I expected this to produce a warning in VS Code:
# switch str to int
class ModelName(int, Enum):
alexnet = "alexnet"
resnet = "resnet"
lenet = "lenet"
But it doesn’t:
<tried to post screenshots but can’t because I’m new>
I do get an error as I try to boot up the application, which is still pretty helpful. At least this would, for example, prevent my application from starting, resulting in it failing health checks, before any production traffic is shifted over to it:
...
class ModelName(int, Enum):
File "/home/matt/.pyenv/versions/3.10.5/lib/python3.10/enum.py", line 289, in __new__
enum_member = __new__(enum_class, *args)
ValueError: invalid literal for int() with base 10: 'alexnet'
I do have autopep8
installed under my dev dependencies in my pyproject.toml
file. VS Code prompted me to install a static analysis tool when I first tried to use “Format Document”, and it automatically installed that dependency when I accepted the prompt. I think I do have static code analysis working in VS Code in general, because some other errors do cause warnings:
<tried to post screenshot but can’t because I’m new>
Is this feature something the type hinting system in Python is meant to support? To be able to detect problems like this before code is executed?