Hacker News new | past | comments | ask | show | jobs | submit login
Refactoring Python dicts to proper classes (nibblestew.blogspot.com)
3 points by ingve 8 months ago | hide | past | favorite | 3 comments



An alternative technique I've used successfully:

1. Declare a class based on TypedDict and add it as a type annotation to the field that holds your dictionary.

2. Run your type checker and fix all type validation issues, if it reports any.

3. For every call site that uses any dict facility other than get/set (if there are any), define methods in your class and change the call site to use those. Note that this step is the same thing as the whole technique that the article is about, just with the twist that you only have to do this for operations that are not get nor set, which are likely to be few and far between.

4. Remove the `TypedDict` mixin from your class. At the same time, replace all the dict get/set invocations with plain property interactions. (You can do this safely in one fell swoop, because the type checker has your back.) If everything passes the type check, you're done.


Yes! TypedDict is fantastic for migrating dicts that have outgrown, into more appropriate containers, such as dataclasses. So good in fact that you can often skip step 3 and 4. Assuming the rest of your code has the type annotations wherever such objects are passed through, otherwise the runtime check from the article still has some merit.


Good point, my silent assumption was that the type checker is configured to enforce function signatures to be fully type-annotated.

(That's one of the first things I change in the mypy config every time I start a new Python project.)




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: