Using get_type_hints() with cyclic imports

This probably isn’t the answer you were hoping for, but…

I recommend against using TYPE_CHECKING conditionals to work around cyclical imports even for static typing. It may seem like a convenient and expedient solution, but it’s masking a deeper structural problem in your code. If you have cyclical imports, that means your code is not well layered, and your code should be refactored.

If you’re using pyright as a type checker, you can enable the reportImportCycles check to report any import cycles within your code. I always enable this rule for my team’s code bases because it enforces good architectural layering. It also eliminates issues with get_type_hints.

1 Like