简体   繁体   中英

Python Type Hinting: How do I enforce that project wide?

My entire team believes type hinting in Python is going to help us build code that will be a lot more maintainable. Everyone is on board with implementing type hinting across our entire project.

After using mypy for a week, we realized mypy doesn't really do much to remind you about implementing type hinting. If you forget to implement type hinting, mypy wouldn't warn. Ideally, we want something similar to flake8 that can lint and warn developers whenever there is undesirable behavior.

What does your organization do to force (as much as possible) type hinting across python projects?

We use Visual Studio with Python Extension if that matters.

Mypy comes with command line options that let you configure how strictly it type-checks your code. These command line options can also be expressed in a config file that mypy will automatically read from if present.

For example, if you want mypy to report a warning if some function does not have types, you'd want to use the --disallow-untyped-defs command line flag. Alternatively, use the --strict flag, which enables this flag along with several other useful ones. (Run mypy --help for the latest description of what --strict enables).

In order to ensure that everybody in your organization is type-checking code in the same way, I recommend committing a mypy.ini config file to your repo with the settings you want to use. For example, here's the config file I use when I want mypy to type-check code to the most paranoid extent possible:

[mypy]
# Disallow dynamic typing
disallow_any_unimported = True
disallow_any_expr = True
disallow_any_decorated = True
disallow_any_generics = True
disallow_any_explicit = True
disallow_subclassing_any = True

# Disallow untyped definitions and calls
disallow_untyped_calls = True
disallow_untyped_defs = True
disallow_incomplete_defs = True
check_untyped_defs = True
disallow_untyped_decorators = True

# None and optional handling
no_implicit_optional = True

# Configuring warnings
warn_unused_ignores = True
warn_no_return = True
warn_return_any = True
warn_redundant_casts = True

# Misc things
strict_equality = True

# Config file
warn_unused_configs = True

This config is almost certainly too aggressive for actual production use. In particular, you'll likely want to disable some of the "disable dynamic typing" options either globally or on a per-module basis, especially if your codebase needs to make extensive use of untyped third party libraries.

You may also want to find some way of pinning the exact version of mypy your devs are using -- the mypy docs recommend setting up some sort of runner script to do these sorts of things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM