Why I Prefer Gradual Typing
I'm no expert in writing type signatures for my Python code. But I find having to litter my code with robust error/condition checking during development takes me out of my flow state.
Before
Here's a contrived example:
def handle_user(user):
questionnaire = questionnaires[user.tenant.slug]
...
# Rest of code omitted
In this 'happy path' code I've made the following assumptions:
- The user has a tenant
- That tenant has a slug
- That slug exists in the questionnaires dictionary
Mypy would rightfully complain about all these things.
Gradual Typing
Personally, thinking in terms of types at this stage feels like a distraction. I'm trying to solve a business problem, not trying to appease mypy & solve typing puzzles.
I often find myself getting stuck on specific typing related issues1, and falling down a rabbit hole of trying to 'Fix the types' before moving on. Eventually I'll solve the issue, but by point I've completely forgotten what I was originally trying to do.
At this point this code completely throwaway, it may not even be the correct approach. So any time spent fighting the type checker only for code to be discarded feels like additional waste.
Only when I'm confident the happy path code works will I go back and retrospectively add any necessary types & robust conditional checks. The final code might look something like this:
After
def handle_user(user: "User") -> None:
if user.tenant is None:
logger.debug(f"No tenant for user: {user}")
return
if not user.tenant.slug:
logger.debug(f"No slug for tenant: {user.tenant}")
return
questionnaire = questionnaires.get(user.tenant.slug)
if questionnaire is None:
logger.debug(f"No questionnaire for tenant {user.tenant.slug}")
return None
I find that this approach gives me a best of both words. I'm able to quickly write code to satisfy the happy path without being distracted or worrying about how 'robust' my approach is.
But by the time the code arrives in production I'll have added in all the necessary defensive code.
If you're familiar with the advantages of gradual typing you'll likely have heard all these same arguments before.
There's probably a point at which this approach doesn't scale, but so far I've found this works best for me.
Skill Issue↩