Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

Tools for static type checking in Python

I'm working with a large existing Python codebase and would like to start adding in type annotations so I can get some level of static checking. I'm imagining something like Erlang, Strongtalk, or Typed Scheme/Racket.

I've seen quick-and-dirty decorators that insert dynamic checks based on function parameter and return type annotations, but I'm looking for something that is more robust and that performs checks at compile-time.

What tools are available right now for this kind of thing? I'm familiar with compilers and type checking and am definitely willing to improve an incomplete tool if it has a good foundation.

(Note: I'm not interested in a discussion of the pros/cons of static typing.)

EDIT: An example:

def put(d, k, v):
   d[k] = v

I'd like to be able to annotate the put function as having type put<K,V>(dict<K,V>, K, V) -> None.

UPDATE: The new PEP 484 (Sep 2014) defines a standard for static typing and type annotations in Python 3.5+. There's a type-checking tool called mypy that is compatible with PEP 484.

question from:https://stackoverflow.com/questions/6025714/tools-for-static-type-checking-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Edit 2016-11-11: Just use mypy. Type hints can be added gradually. In Python 3 source code, it verifies standard PEP 484 type hints. Types can still be expressed in Python 2 using special comments. Guido likes it.

This post was originally written a long time ago before mypy was a thing. I've preserved the post's original content below, even though it isn't quite accurate.


Original post:

You might want to check out some of the projects mentioned in this related StackOverflow post on static analysis for Python.

In summary:

Since Python uses duck typing extensively, things that might be called "type errors" in other languages might end up being "object X doesn't support method Y" in Python.

Edit 2011-05-17:

I agree with delnan that static typing is not possible for Python [apparently wrong]. But since our skepticism doesn't seem to deter you, I can only give you more information on the subject. I present:

  • A discussion of type inference for Python. (Other links are from here.)
  • Guido van van Rossum's articles on adding optional static typing: part 1 and part 2.
  • RPython, a subset of Python that might stand a chance of being statically analyzed enough to do some form of type checking.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...