Hacker News new | ask | show | jobs
by andrewcooke 5015 days ago
why doesn't this use the python standard for adding type information? it should be:

   def foo(n: int):
not

   def foo(int n):
then it would be valid python 3 code (and would also work with pytyp (disclaimer: mine)).

http://docs.python.org/py3k/reference/compound_stmts.html#fu... http://www.python.org/dev/peps/pep-3107/ http://www.acooke.org/pytyp/

2 comments

Thanks for mentioning pytyp!

I have been using this recipe: http://code.activestate.com/recipes/572161/ to add type checking to Python for a while now, so it's nice to see a more mature and developed library that does the same (and more.)

In your code examples I didn't see any decorators around the functions that were being typechecked, so how do you then enforce the type checking?

In addition, is pytyp as fully-featured as the recipe above? (The recipe is short but well-written.) The comments at the beginning of the recipe shows a bunch of examples that demonstrate all that it can do.

huh. i will fix that, thanks. there should be a @checked annotation on the function that is checked in the example there.

pyptyp is pretty comprehensive. for example, Rec(a=Seq(Opt(int)),b=Alt(float,str)) is the type for something like a dict where a is a list that contains ints or None and b is either a float or a string.

BUT it's pure python so it's not at all fast. i wouldn't use type checking throughout a codebase - only for debugging, or tests.

it's perhaps more useful as a start for building other things. for example, it includes mapping from JSON to python objects - it can use type annotations to guide the construction of python objects from JSON lists and maps. but on the other hand the internals are quite complex (i have been working with it recently, after not using it for a year or so, and it's taken some effort to understand everything).

Another similar project: https://github.com/podio/valideer. The (rough) equivalent schema for the example above can be expressed as {"a": ["?integer"], "b": AnyOf("number", "string")}.
also, i should perhaps mention, compared to some other libraries, pytyp is integrated with ABCs and the Python type system. so you can use isinstance() with these expressions, for example.
Mypy needs some extra syntax not provided by standard Python annotations (e.g. local variable annotations, casts), so it makes sense to have the syntax related to static typing clearly different from Python to avoid confusion. C-style annotation syntax also has the benefit of being familiar to a very large programmer population. There will also be a converter from mypy syntax to Python syntax.
just seen this reply; thanks. i encourage you to think again, though. one reason is that you would be more likely to influence the future evolution of python itself if you worked more within the system...