摘要: Mypy, Pytype, Pyright, and Pyre can help you keep your type-hinted Python code bug-free. Let’s see what each of these useful tools has to offer

 


code clean

▲圖片標題(來源:Serdar Yegulalp)

In the beginning, Python had no type decorations. That fit with the overall goal of making the language fast and easy to work with, with flexible object types that accomodate the twists and turns of writing code and help developers keep their code concise.

Over the last few years, though, Python has added support for type annotations, inspiring a whole culture of software devoted to type checking Python during development. Python doesn’t check types at runtime — at least, not yet. But by taking advantage of a good type checker, riding shotgun with you in your IDE of choice, you can use Python’s type annotations to screen out many common mistakes before they hit production.

In this article we’ll delve into four of the major type checking add-ons for Python. All follow roughly the same pattern, scanning Python code with type annotations and providing feedback. But each one offers its own useful additions to the basic concept.

Mypy

Mypy was arguably the first static type checking system for Python, as work on it began in 2012, and it’s still under active development. It is essentially the prototype for how third-party type checking libraries work in Python, even if many others have come along since and expanded on its features.

Mypy can run standalone, or from the command line, or it can work as part of an editor or IDE’s linter integration. Many editors and IDEs integrate Mypy; Visual Studio Code’s Python extension can work with it directly. When run, Mypy generates reports about your code’s consistency based on the type information it provides.

If your code doesn’t include type annotations, Mypy will not perform the vast majority of its code checks. However, you can use Mypy to flag unannotated code. This can be done with varying degrees of strictness depending on one’s needs.

If you’re starting from scratch with a codebase and you want a preemptively aggressive linting strategy, you can use the --strict option to prevent any untyped code. On the other hand, if you’re working with a legacy codebase that doesn’t have many type definitions, you can use more relaxed options such as preventing only untyped function definitions with --disallow-untyped-defs while allowing other untyped code. And you can always use inline comments like # type: ignore to keep individual lines from being flagged.

Mypy can make use of PEP 484 stub files when you want to use type hints for a module’s public interfaces. On top of this, Mypy offers stubgen, a tool that automatically generates stub files from existing code. For untyped code the stub files use generic types, which you can then mark up as needed.

詳見全文 Full Text: InfoWorld

若喜歡本文,請關注我們的臉書 Please Like our Facebook Page:    Big Data In Finance

 


留下你的回應

以訪客張貼回應

0
  • 找不到回應

Popular Tags