|
|
Subscribe / Log in / New account

Type hinting for Python

By Jake Edge
December 24, 2014

Python is a poster child for dynamically typed languages, but if Guido van Rossum gets his way—as benevolent dictator for life (BDFL), he usually does—the language will soon get optional support for static type-checking. The discussion and debate has played out since August (at least), but Van Rossum has just posted a proposal that targets Python 3.5, which is due in September 2015, for including this "type hinting" feature. Unlike many languages (e.g. C, C++, Java), Python's static type-checking would be optional—programs can still be run even if the static checker has complaints.

Static vs. dynamic type checking is one of the big religious wars in computer language design. Statically typed languages rigidly enforce the rules on the types that can be assigned to variables or passed to functions, typically refusing to compile or run programs that violate those rules. Dynamically typed (some of which, like Python, are known as "duck typed") languages, on the other hand, allow an object of any type to be assigned to any variable or passed to any function, which adds a great deal of flexibility, but can also lead to runtime errors that could never occur in a statically typed program.

Both type systems have merits—and proponents—but they are usually mutually exclusive in a particular language. Either dynamic or static typing is inherent in the language's design, so it is rare to have both. What Van Rossum is proposing is to adopt the notation used by the mypy static type-checker for Python to, optionally, specify the types of function parameters and their return types, along with the types of variables. That would allow a static type-checker (either mypy or something else) to reason (and complain) about the wrong types being used.

For function argument and return types, the syntax to annotate functions is already present in Python 3, and has been since its first release. It is a little-used feature that was put into the language to see where it led. One of those outcomes was mypy. Function annotation is fairly straightforward:

    def foo(a, b: int, c: str) -> str:
        pass
That defines a do-nothing function that takes two integers and a string as arguments and returns a string. For those unfamiliar with Python, the "normal" definition of that function would look like:
    def foo(a, b, c):
        pass
As might be guessed, user-defined class names can be used, as can various built-in aggregation types (e.g. List[int] or Dict[str, int]). Python function annotations are completely open-ended (just associating some value with each function argument and its return value), so the conventions used to specify type information are largely derived from mypy (which has good documentation that includes the type conventions).

There is not yet a Python Enhancement Proposal (PEP) for type hinting, though there is work in progress on one. In addition, Van Rossum has put together a theory document that he referenced in his proposal. It describes a new relationship ("is-consistent-with") between types; if type t1 is a subclass of t2, t1 is consistent with t2 (but not vice versa). The Any type is kind of a wildcard, it is consistent with every type (but Any is not a subclass of any other type) and every type is a subclass of Any (thus consistent with it).

Those simple rules allow various kinds of reasoning about the types that get assigned to variables and passed to functions. Van Rossum's ideas come from a number of sources, but "gradual typing" is clearly central to his thinking. His theory document refers those looking for "a longer explanation and motivation" to a gradual typing blog post from Jeremy Siek. It is, essentially, a blueprint for providing both static and dynamic typing for a language.

There is more to type hinting than just function annotations, however. The proposal does not add any syntax to the language for declaring variables to be a certain type, so comments with a specific format are used:

    x = {}    # type: Dict[str, str]
That would declare x to be a dictionary with strings as both keys and values.

For situations where there are several options for types, the Union type can be used:

    def feed(a: Union[Animal, Sequence[Animal]]) -> bool:
        pass
That allows the argument a to either be an instance of the Animal class or a sequence of Animals (or, of course, any type that is-consistent-with those). feed() returns True or False. To simplify types in declarations, aliases can be used:
    point = Tuple[float, float]

    def distance(a, b: point) -> float:
        pass
Forward references are handled by strings with the type name that are to be evaluated later:
    class C:
        def foo(self, other: 'C') -> int:
            pass
The class C is being referred to before it is defined, so using the name as a string (i.e. 'C') avoids the forward reference.

There is more, of course, but that should give a reasonable flavor of the proposal. Van Rossum has chosen a fairly aggressive schedule for adding the feature, which he acknowledged in his message:

I am still hoping to get a PEP out for discussion in early January, and I am aiming for provisional acceptance by PyCon Montréal, which should allow a first version of typing.py to be included with Python 3.5 alpha 4. If you are wondering how I can possibly meet that schedule: (a) the entire runtime component proposal can be implemented as a single pure-Python module: hence the use of square brackets for generic types; (b) a static type checker is not part of the proposal: you can use mypy, or write your own.

The reaction has been largely positive. Part of the reason is that the feature only affects those few who are already using function annotations in some other way (which won't break, at least yet) or who want some amount of static checking added to the language. While there are other ways to do so, Van Rossum's approach is minimally intrusive—it doesn't change the language at all—so those who want to can simply ignore it entirely.

It will be interesting to watch this feature play out over the coming months. Even more interesting, though, will be seeing what uses Python developers find for a standardized static type system. Certain kinds of large projects and organizations are likely to benefit from static typing, so some pieces that might have been written in other languages may stick with Python instead. In any case, it is yet more evidence that Python has come a long way since its genesis in the late 1980s.



to post comments

Type hinting for Python

Posted Dec 24, 2014 23:24 UTC (Wed) by juliank (guest, #45896) [Link] (10 responses)

I don't like assigning semantics to comments, but otherwise, I welcome this idea.

Type hinting for Python

Posted Dec 25, 2014 0:41 UTC (Thu) by josh (subscriber, #17465) [Link] (4 responses)

I agree; given that Python already has syntax for annotating function arguments, why not just add syntax to annotate the LHS of an expression? For instance:

a: Dict[str, str] = {}

To the best of my knowledge, that wouldn't conflict with anything.

Type hinting for Python

Posted Dec 26, 2014 4:22 UTC (Fri) by mathstuf (subscriber, #69389) [Link] (3 responses)

This would require new syntax and therefore be backwards incompatible. Personally, I'd rather docstrings or expression decorators, but I've become so jaded with Python I find it hard to care too much what they do with 3.5 since I'm still fighting to get to 3.0.

Type hinting for Python

Posted Dec 26, 2014 6:06 UTC (Fri) by josh (subscriber, #17465) [Link] (2 responses)

> This would require new syntax and therefore be backwards incompatible.

As in, code written to use types would not work with Python pre-3.5?

That really doesn't seem like a problem. Plenty of code currently requires 2.7 and won't work with 2.6, for instance.

Type hinting for Python

Posted Dec 27, 2014 3:28 UTC (Sat) by mathstuf (subscriber, #69389) [Link] (1 responses)

Python has gotten a lot of flak for breaking compatibility already and it seems they're taking further steps in that direction carefully which I prefer to "eh, you should use the latest anyways". Not everyone has such a luxury :( .

Type hinting for Python

Posted Dec 29, 2014 18:14 UTC (Mon) by iabervon (subscriber, #722) [Link]

Changes where some files that previously would have given syntax errors now don't aren't really a big deal; what they've gotten flak for is changes where files that were previously valid don't do the same thing or are invalid.

In fact, they're technically breaking compatibility more with the comment mechanism, in that a file with comments that are close to being type declarations but aren't quite right for this system will presumably generate whatever effects type mismatches end up having (mitigated somewhat by the fact that doing anything with the annotations won't happen without a proactive step).

Type hinting for Python

Posted Dec 25, 2014 0:46 UTC (Thu) by proski (subscriber, #104) [Link] (3 responses)

I agree. Comments are comments - they are highlighted in a specific way, they are seen as a message from the code author to the human reading the code. It should be possible to declare the type of a variable and comment on its purpose, on the same line.

Code in comments, really?

Posted Dec 25, 2014 1:07 UTC (Thu) by marcH (subscriber, #57642) [Link]

> Comments are comments - they are highlighted in a specific way, they are seen as a message from the code author to the human reading the code.

If only humans were the only potential problem. A lot of "meta" development tools (editors, IDEs, etc.) read comments too. Imagine their confusion now.

Code in comments, what an horror. Not familiar enough with Python for this question, but isn't there some concept of "annotations" as a much better solution here?

Type hinting for Python

Posted Dec 25, 2014 8:47 UTC (Thu) by epa (subscriber, #39769) [Link] (1 responses)

You have to wonder what is so special about this language feature that it has to rely on magic comments, while many other (arguably more significant) language changes to Python have been made in the core language, introducing a backwards-incompatible change if necessary. And what happens when the next language change is considered?

Type hinting for Python

Posted Jan 2, 2015 0:52 UTC (Fri) by smitty_one_each (subscriber, #28989) [Link]

The 'special' nature of it is that Python is trying to have it many ways:
- stay totally dynamic, and not need any type hinting
- don't create incompatibilities
- allow types in for those keen on the feature
Python is a great tool, and the BDFL will settle on something.

Type hinting for Python

Posted Dec 29, 2014 23:40 UTC (Mon) by debacle (subscriber, #7114) [Link]

Same here. I'ld rather accept an incompatible language change than abusing comments for type declaration. At least, backporting such code to Python < 3.5whatever would only mean to remove the declaration. Similar to backporting ANSI C code to K&R.

Type inference

Posted Dec 25, 2014 1:02 UTC (Thu) by marcH (subscriber, #57642) [Link] (2 responses)

Just for completeness (don't think it can apply to Python), static typing does not always require declaring types: http://en.wikipedia.org/wiki/Type_inference

The productivity boost of having many errors detected at compile time without having to explicit any typing is a coding experience one seldom forgets. It also makes refactoring MUCH faster.

Type inference

Posted Dec 25, 2014 15:46 UTC (Thu) by deepfire (guest, #26138) [Link]

This is basically why I have abandoned untyped languages (even if my heart used to be with Common Lisp) -- because I tend to work on systems large enough they don't fit in my head.

Maintaining such programs without a type system helping preserve correctness becomes way too painful. It removes fun from programming.

Type inference

Posted Dec 25, 2014 23:41 UTC (Thu) by ofranja (guest, #11084) [Link]

That's usually one of the points that comes up when I'm arguing with someone that insists that dynamically typed code is more "general" that static typed code.

HM type systems, for instance, turn programming into something much simpler without requiring one to drop the safety guarantees. Together with features like type classes, functors or traits it also makes reasoning about properties more important that the code itself. It becames easier to connect different parts of the code because you start dealing directly with concepts/abstractions and transformations.

Last, but not least, there's also something that you can enforce on (good) typed languages: making inconsistent states unrepresentable. This rules out a lot of extraneous error checking and makes the code much more reliable.

Type hinting for Python

Posted Dec 25, 2014 1:46 UTC (Thu) by rsidd (subscriber, #2582) [Link] (2 responses)

I wish they had made it compatible with cython, which has optional typing too and is very widwly used by people who want speed.

Type hinting for Python

Posted Dec 26, 2014 15:00 UTC (Fri) by mb (subscriber, #50428) [Link]

Cython is way too low level, IMO.
If you completely annotate a Cython program with type information, it looks like plain C with missing curly braces.

That said, I would really be interested in the Python optimizer picking up information from the optional static typing to speed up the program. _Without_ an additional (actually two) compilation stage, as with Cython.
Sure, that won't be as fast as Cython, but it would be more ideomatic to Python.

However: That type-information-in-comments thing is awful. Comments are comments. Not code.

Type hinting for Python

Posted Jan 14, 2015 22:02 UTC (Wed) by njs (subscriber, #40338) [Link]

There was some discussion of this in the python-dev thread, including the Cython developers weighing in.

Short version: the Python type system is pretty much useless for speeding anything up, b/c just knowing that some variable IS-A 'dict' object tells you literally nothing about how it acts -- it's legal to subclass 'dict' and override all methods. (It's a terrible idea to do this, Liskov blah blah, but the language doesn't forbid it.) The types Cython adds are all assertions about C memory layout and C level semantics, which is a totally different and inconsistent system from Python types. And Python isn't going to grow a whole new type system any time soon, so speedups and Cython compatibility are pretty much off the table here.

This type-hinting stuff IIUC has a totally different and orthogonal goal, which is to let developers quickly check assertions like "I caught all the old places that assumed this variable was a tuple instead of the class I just upgraded it to" (without having to write 100% coverage test-suites), or IDEs to provide better suggestions/autocompletion. Stuff like that. Kinda disappointing if you were hoping for the other kind of type assertions, but useful.

Type hinting for Python

Posted Dec 25, 2014 4:35 UTC (Thu) by smitty_one_each (subscriber, #28989) [Link]

>Van Rossum's approach is minimally intrusive—it doesn't change the language at all—so those who want to can simply ignore it entirely.

That sounds like Famous Last Words.
Will there be a rule precluding type checking in all of the Python standard library?

Type hinting for Python

Posted Dec 25, 2014 4:58 UTC (Thu) by fandingo (guest, #67019) [Link] (10 responses)

*args, **kwargs are substantial features of Python function declarations. It's great to see a proposal that doesn't offer any commentary, let alone *any* sort of solution. I write Python applications for a living, and I understand the appeal of this feature, but it's misguided. It's violating the basic zen of Python:

> Beautiful is better than ugly.

While there may not be a more beautiful way to express partial typing, it doesn't change the fact that this is ugly.

> Simple is better than complex.

Definitely not simple.

> Complex is better than complicated.

Looks complicated, especially the generic -- um Union, Any, *, object? -- types. Why are `list` and `dict` capitalized? That's inconsistent with the rest of the language. So you'd use `Dict[int, str]`, but why is Dict capitalized and int/str lower case (which is how Dict/List should be)? Inconsistent.

> Sparse is better than dense.

Something more like decorators would keep the density reasonable, especially since this is totally optional, and even then, not rigid.

> Readability counts.

Adds way more optional stuff to lines that already tend to be long and wrapped.

> If the implementation is hard to explain, it's a bad idea.

Union types? Forward type definitions? Using colons in a novel way? None of that is conventional for Python, let alone easy to explain. Plus, even when used, it's not causing static type behavior: program crash or failure to compile, so it's not even consistent with what it seems to profess to do.

> Errors should never pass silently.
> Unless explicitly silenced.

>> Python's static type-checking would be optional—programs can still be run even if the static checker has complaints.

What???? The static checker either needs to raise exceptions that must be handled, although who knows how you would try/except a function declaration, or disappear. This is PHP-execution-continues-even-on-error stupidity.

Python is supposed to be a simple language to write and read. So many of the recent features are chewing up the language and making it something far more complicated. That's fine when confined to modules, even in stdlib, but messing with core concepts of the language is a mistake. Python is a duck-typed language, and messing with that will only damage it. This isn't Pythonic at all.

Type hinting for Python

Posted Dec 25, 2014 6:35 UTC (Thu) by Cyberax (✭ supporter ✭, #52523) [Link] (7 responses)

> *args, **kwargs are substantial features of Python function declarations.
Anyone who uses them should be incarcerated, unless they are used only for argument forwarding.

> Looks complicated, especially the generic -- um Union, Any, *, object? -- types. Why are `list` and `dict` capitalized?
Because right now you can't override the behavior of built-in dicts and lists. The capital letter is right now just a hack to allow the typechecker implementation to run on unmodified CPython or PyPy interpreters.

> What???? The static checker either needs to raise exceptions that must be handled, although who knows how you would try/except a function declaration, or disappear. This is PHP-execution-continues-even-on-error stupidity.
Typechecker is useful for static 'compile-time' checks. It will probably add a non-trivial overhead in runtime if left on.

Type hinting for Python

Posted Dec 25, 2014 14:05 UTC (Thu) by deepfire (guest, #26138) [Link]

> > *args, **kwargs are substantial features of Python function declarations.
> Anyone who uses them should be incarcerated, unless they are
> used only for argument forwarding.

This heavily smacks of religion. I does not approves.

Languages are vehicles for expressing our ideas on problem solution.

Limiting ourselves to preconceived notions of "proper" is.. misuse of our cognitive capacity.

Type hinting for Python

Posted Dec 25, 2014 15:38 UTC (Thu) by deepfire (guest, #26138) [Link] (5 responses)

> Typechecker is useful for static 'compile-time' checks.
> It will probably add a non-trivial overhead in runtime if left on.

There appears to be a lot of confusion in this statement.

First, Python already pays the full price of runtime type checking -- it doesn't have the basis for type erasure because it's an untyped language.

Second, if you mean typechecking of dynamically injected code, such as by AST compilation and subsequent code object loading -- it only happens exactly as often as you perform compilation and loading.

Type hinting for Python

Posted Dec 25, 2014 18:57 UTC (Thu) by Cyberax (✭ supporter ✭, #52523) [Link] (4 responses)

Runtime 'strict' type checking will impose additional penalty compared to the regular Python's typelessness.

For example:
> a = Dict[str,str]()
> a[11] = 'hello'

That's a perfectly legal code with the regular dict() but should not be accepted in a type-checked dialect.

Typechecking on module load makes sense, of course.

Type hinting for Python

Posted Jan 8, 2015 17:21 UTC (Thu) by pboddie (guest, #50784) [Link] (3 responses)

Python isn't typeless, but I guess that's just a bad choice of terminology. Meanwhile, how would "typechecking on module load" work? An innocent-enough question until you have to answer it thoroughly.

Personally, I see this as yet another attempt to placate criticisms of Python programs not being easy enough to analyse or predict, with a dash of optimism about performance benefits, but there's a risk of it ending up in a type specification swamp whilst not managing to offer something as mature as (or with the inferencing conveniences of) something like OCaml or various other functional languages.

Type hinting for Python

Posted Jan 8, 2015 17:39 UTC (Thu) by deepfire (guest, #26138) [Link] (2 responses)

> Python isn't typeless, but I guess that's just a bad choice of terminology.

What I was saying is -- there's no known way to assign types to all expressions of Python. AFAIK, that's the standard lingo in type theory.

> Meanwhile, how would "typechecking on module load" work?

I'm sorry, that was a careless choice of words on my part. What I meant, instead, is just compile-time (AST -> code-object) type checking.

> ..but there's a risk of it ending up in a type specification swamp
> whilst not managing to offer something as mature as (or with the
> inferencing conveniences of) something like OCaml or various other
> functional languages.

This is exactly how I feel, indeed.

Type hinting for Python

Posted Jan 8, 2015 22:45 UTC (Thu) by pboddie (guest, #50784) [Link] (1 responses)

No worries about the terminology: I actually thought it was Cyberax who had been using it, not you.

I've had a fascination for Python code analysis over many years, and things like deducing types can work provided that certain constraints are enforced. Part of the problem is actually being able to conclusively describe the types, and Python always manages to provide loopholes that could, at least in theory, undermine such descriptions and undo all the resulting deductions about the code.

But given some constraints on the language, you can make deductions about types in programs, even reliable ones if the loopholes are eliminated. Some people get upset about this because "it's not Python any more!" but no-one appears to be interested in discussing the nature of Python beyond what's in the Python-3.x.tar.gz file on python.org.

As a result, we now have type annotations requiring a new vocabulary to describe types when it may well be the case that there are more substantial gains to be made in actually simplifying or structuring other aspects of the language, at least for those interested in increased reliability or predictability of Python programs.

Type hinting for Python

Posted Jan 9, 2015 18:33 UTC (Fri) by deepfire (guest, #26138) [Link]

To be honest, as a dynamically-typed (typeless) language, Python is not all that interesting,
since there Common Lisp beats it in almost all departments, except syntax unobtrusiveness.
Tangentially, CL also has optional type annotations, and modern CL compilers do a fairly
useful job at partial type inference, and even provide optimization hints.

As to typing.. why bother with this painful shoe-horning, when there are
beautiful static, inferred, optionally-enforcing[1] languages like Haskell..

--
1. As of 7.8 GHC gained an option to defer type errors to runtime

Type hinting for Python

Posted Dec 27, 2014 5:23 UTC (Sat) by lamawithonel (subscriber, #86149) [Link] (1 responses)

Beautiful is better than ugly.
....
Sparse is better than dense.
Readability counts.

This.

IMHO, rather than declaring the type on the same line this should be done in human-readable documentation, then parsed. Make something like YARD for Python and use that for type hinting-- at least for functions. I do agree that comments should be comments, though; "Special cases aren't special enough to break the rules," as it says in PEP-20 (The Zen of Python). But instead of straight # comments it could be some special syntax within the PEP-8/257 docstring. Kill two birds with one stone.

For variables, I think this bit from PEP-20 could apply:

There should be one...obvious way to do it.

Finding a compatible syntax closer to C or Java type declarations would do best by this, I think. Principle of least surprise and all that.

Of course, PEP-20 also has these things to say...

There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're [in the know.]
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.

Type hinting for Python

Posted Dec 31, 2014 17:25 UTC (Wed) by rds (subscriber, #19403) [Link]

-- Finding a compatible syntax closer to C or Java type declarations
-- would do best by this, I think.

Maybe I'm old, but it looks like Pascal to me.

Type hinting for Python

Posted Dec 25, 2014 13:32 UTC (Thu) by kleptog (subscriber, #1183) [Link]

While the idea seems interesting, like others I agree the syntax is a bit off.

But, Python 3, so the chance I'm going to be able to use this in production is approximately 0. :(

Type hinting for Python

Posted Dec 25, 2014 14:01 UTC (Thu) by deepfire (guest, #26138) [Link] (2 responses)

Interestingly, since 7.8.2 Haskell/GHC allows deferring type errors to runtime:

https://downloads.haskell.org/~ghc/7.8.2/docs/html/users_...

TLDR: -fdefer-type-errors enables pythonesque usage of Haskell.

Informally

Posted Jan 2, 2015 0:57 UTC (Fri) by smitty_one_each (subscriber, #28989) [Link] (1 responses)

Informally, do they call this feature "moan-add"?

Informally

Posted Jan 4, 2015 21:39 UTC (Sun) by jzbiciak (guest, #5246) [Link]

*groan*

But it must change the language

Posted Dec 26, 2014 18:23 UTC (Fri) by southey (guest, #9466) [Link] (5 responses)

Van Rossum's approach is minimally intrusive—it doesn't change the language at all.
At least this introduces new types to the language since you have now have static types in addition to the previous dynamic types. Consequently you can no longer assume that you can do anything with any variable when the type checking is enforced. For example, adding a float to an statically defined X integer would an error yet old Python says X must change to a float. Or updating a dictionary when the value type is a float but the new value is a integer should be an error. More complex is any error checking on the type conversion as usually you define a static type so that it remains that type.

It just gets worse once you think about how variable can be used. For example, what will be the rules when accessing 'old' code with statically typed variable? Dropping the statically typed requirements would defeat the purpose of using static types but enforcing it will likely result in errors.

But it must change the language

Posted Jan 13, 2015 18:03 UTC (Tue) by Wol (subscriber, #4433) [Link] (4 responses)

But this is all computer science stuff. Why can't we just have numbers that are numbers :-)

If you're moving from a dynamic typing system to a static typing system you don't want "int" and "float", you want "number". So you can add "6" and "3.1" without worrying about the program blowing up with a "wrong sort of number" error.

Try looking at the problem from a "real world" perspective, not from a theoretical mathematical perspective, sometimes ... :-)

Cheers,
Wol

But it must change the language

Posted Jan 13, 2015 19:27 UTC (Tue) by cesarb (subscriber, #6266) [Link] (3 responses)

> But this is all computer science stuff. Why can't we just have numbers that are numbers :-)

For which definition of number? N? Z? Q? R? C?

> Try looking at the problem from a "real world" perspective, not from a theoretical mathematical perspective, sometimes ... :-)

All of these except perhaps C come from the "real world".

In related news: the Lua language, which had previously used "float" for everything, now has both 64-bit "int" and "float" in the just released 5.3 version. See these slides: http://www.inf.puc-rio.br/~roberto/talks/ws2014.pdf (found at https://news.ycombinator.com/item?id=8874766).

But it must change the language

Posted Jan 13, 2015 20:40 UTC (Tue) by mpr22 (subscriber, #60784) [Link] (2 responses)

Even complex numbers relate to the physical world; analysing alternating-current electrical systems without them is painful.

But it must change the language

Posted Jan 13, 2015 22:19 UTC (Tue) by mathstuf (subscriber, #69389) [Link] (1 responses)

Yep. The geometric interpretation of multiplication by sqrt(-1) is a turn of π/2 radians. "Imaginary" is a really poor name for them since it really just comes from the lack of an imagination by mathematicians when they were first being investigated. Likewise, quaternions can be viewed as an axis on a sphere with an "up" vector off of the oriented radius. I haven't worked with octonions enough to have a real-world example for them (and since their algebras start to break down anyways, they're much harder to conceptualize as well). Wiki suggests they're used in things such as string theory and other (relativity-related) physics subfields though.

But it must change the language

Posted Jan 14, 2015 0:35 UTC (Wed) by gracinet (guest, #89400) [Link]

I think the naming is historically due to Cardano's trick of assuming existence of « imaginary » solutions of the auxiliary 2nd degree equations that are used for solving 3rd degree equations in the case where the discriminant is negative, in a trick that must have looked incredibly artificial at the time. *That* was thinking out of the box !

The geometric interpretations came much later, and while useful in countless cases, it's just one way to think about complex numbers, that's not adapted to all settings.

Anyway, getting back on topic, sorry.

Type hinting for JavaScript

Posted Dec 27, 2014 9:56 UTC (Sat) by Tragetaschen (guest, #98000) [Link] (1 responses)

This looks a lot like TypeScript: http://www.typescriptlang.org/

Type hinting for JavaScript

Posted Dec 27, 2014 13:33 UTC (Sat) by Lennie (subscriber, #49641) [Link]

Javascript has done almost everything it can (except what Python might be doing now) to include types where it can while remaining a dynamically typed language.

Yes, using one of the 'transpilers'/compilers like TypeScript is one way:
https://github.com/jashkenas/coffeescript/wiki/list-of-la...

By adding support for typed arrays (was needed for WebGL, but now used for lots of other things):
https://developer.mozilla.org/en-US/docs/Web/JavaScript/T...

As was already mentioned above in comment, TypeInference can also be used, most if not all Javascript engines support TypeInference at runtime to optimize the JIT compilation process:
https://wiki.mozilla.org/TypeInference

asm.js introduced a standardised form of type hinting:
http://asmjs.org/spec/latest/#parameter-type-annotations

So the JIT compiler knows how to compile it without ambiguity and thus not having to compile in any fallback code. Which for example means better use of the CPU caches.

Explicit vs implicit typing

Posted Dec 27, 2014 11:37 UTC (Sat) by jnareb (subscriber, #46500) [Link]

There is a bit of conflation between static versus dynamic typing (variable has assigned type statically at compilation time, or can change type at runtime dynamically), and explicit versus implicit typing (stating type explicitly, or deriving type from value with type inference).

You can have implicit typing in C++14, a classic static typed language, with the 'auto' keyword.

Reinventing Dialyzer for Python?

Posted Dec 28, 2014 15:20 UTC (Sun) by NAR (subscriber, #1313) [Link] (4 responses)

This looks very much like Dialyzer for Erlang. Of course, the Erlang solution is neater because it did modify the language (new -spec type specifications), so there's no need to abuse comments. I've used Dialyzer on a fairly large project, about 95% of the errors it found were in error handling (thus never tested) code. However, that project had fairly good test coverage so the errors Dialyzer could had found were usually found by normal tests earlier. The main drawback was that Dialyzer was quite slow (ran in matter of hours, not minutes or seconds, so we never ran interactively, only nightly). On the other hand it helped with documentation and keeping the documentation in sync with the code. So don't expect miracles in Python: if a product is well tested, the static analyzer won't find many real errors. If it is not well tested, the product is screwed anyway.

Reinventing Dialyzer for Python?

Posted Dec 28, 2014 16:44 UTC (Sun) by deepfire (guest, #26138) [Link] (3 responses)

> if a product is well tested, the static analyzer won't find many real errors.

Is this meant to be a general statement, or does it apply to the specific kind of the type system that you find to be similar to Dialyzer's?

If it is the former..

Don't you think that the efficiency of the type system at catching errors entirely depends on the type system in question?

Reinventing Dialyzer for Python?

Posted Dec 29, 2014 9:16 UTC (Mon) by NAR (subscriber, #1313) [Link] (2 responses)

I think the key here is "well tested". If someone adds a new function in a dynamically typed language, adds a call to this function, then tests the call, it gives stronger guarantees about program correctness than a statically typed language's compiler which only checks that the correct types are passed, but cannot check that the function does what it supposed to do. The other key thing is that with a dynamically typed language the "write code-execute test" cycle can be faster than the "write code-compile" cycle of e.g. C++.

Reinventing Dialyzer for Python?

Posted Jan 9, 2015 18:37 UTC (Fri) by deepfire (guest, #26138) [Link] (1 responses)

What you don't seem to understand, is that /expressive type systems/ allow you to encode part of your correctness constraints into the source code.

This one fact is hard to overstate. The impact on correctness it has approaches that of formal verification.

But of course, in order to appreciate that, one has to be actually familiar with expressing programs in those advanced type systems.

Reinventing Dialyzer for Python?

Posted Jan 9, 2015 20:16 UTC (Fri) by mathstuf (subscriber, #69389) [Link]

This[1] might be relevant.

[1]http://r6.ca/blog/20120708T122219Z.html

Type hinting for Python

Posted Dec 29, 2014 15:11 UTC (Mon) by kjp (guest, #39639) [Link] (1 responses)

This could be big if it addresses *all* of the following:

- class method does not exist (when used by someone very far away from its construction)
- module level function does not exist
- module level 'constant' does not exist, e.g. module.SOME_CONSTANT_TYPO. I suppose you could (maybe?) convert this to static class members, but really if it can't solve this it would be pathetic.

I like that they addressed nullable arguments specifically, but they're late to the party there.

Type hinting for Python

Posted Jan 4, 2015 17:32 UTC (Sun) by mathstuf (subscriber, #69389) [Link]

How would you annotate something like map or filter? Is there a way to reference the types of other parameters for polymorphic or higher-kinded functions?

Type hinting for Python

Posted Jan 9, 2015 15:12 UTC (Fri) by runciter (guest, #75370) [Link]

This looks an awful lot like Perl 6 to me, only in Perl 6 it is not an afterthought.

Type hinting for Python

Posted Jan 10, 2015 9:37 UTC (Sat) by Endeios (guest, #58183) [Link]

As of 9 jan 2015 this is now a PEP

Type hinting for Python

Posted Jan 14, 2015 14:58 UTC (Wed) by nye (subscriber, #51576) [Link] (5 responses)

>The proposal does not add any syntax to the language for declaring variables to be a certain type, so comments with a specific format are used:

> x = {} # type: Dict[str, str]

That sound you can't hear is me sucking in air between my teeth.

I've always found Python's syntax to be distressingly inelegant, but this implies to me that there are actually no limits to how bad it might get.

If this was the least bad solution they could come up with, I can't even *imagine* what else they might have considered.

Type hinting for Python

Posted Jan 14, 2015 16:55 UTC (Wed) by flussence (guest, #85566) [Link] (3 responses)

>If this was the least bad solution they could come up with, I can't even *imagine* what else they might have considered.

Python 4.0? I guess they didn't go for syntax breakage because everyone's still(!) picking up the pieces from the 3.0 split.

Type hinting for Python

Posted Jan 14, 2015 17:07 UTC (Wed) by andresfreund (subscriber, #69562) [Link] (2 responses)

> >If this was the least bad solution they could come up with, I can't even *imagine* what else they might have considered.

> Python 4.0? I guess they didn't go for syntax breakage because everyone's still(!) picking up the pieces from the 3.0 split.

Introducing new syntax for new features is hardly the same thing as breaking stuff all around so that old code doesn't run with new versions of the language (interpreters). Python has introduced new features in language versions for a long while before 3.0, without a lot of complaints.

Type hinting for Python

Posted Jan 14, 2015 18:15 UTC (Wed) by nye (subscriber, #51576) [Link] (1 responses)

Yes, I don't understand why they feel it's worth going to such extraordinary lengths to ensure that code written in the future to use this additional feature should be able to run unmodified - but without the feature working - in old versions of Python 3.

If this were a change that could prevent today's code from running on tomorrow's Python then that would be a different thing[0], but loads of Python releases have introduced new features that prevent your code running on older versions if you choose to use them. And loads of releases for other languages - it's standard practice.

As it stands, it sounds like this syntax is intended purely as a stopgap measure anyway, to see how well the feature is received, which doesn't exactly make me feel more positive about it.

[0] although in principle the fact that suddenly comments have meaning to the compiler does mean that, this way, it actually *is* possible that today's code might not work in tomorrow's Python, though hopefully it's unlikely anyone will have comments in that format.

Type hinting for Python

Posted Jan 14, 2015 19:29 UTC (Wed) by mathstuf (subscriber, #69389) [Link]

Doesn't Python have some magic comments at the top of a file already for character encoding? Why not bless files with the comment to do comment-based type checking and just warn in other cases?

Type hinting for Python

Posted Jan 14, 2015 21:51 UTC (Wed) by njs (subscriber, #40338) [Link]

They're documenting/formalizing a syntax that was originally defined by a third-party tool, as part of the process of standardizing such tools, while making zero changes to Python itself. If it works and people end up caring about this stuff then after gathering some experience they probably will make some minimal changes to Python's syntax to let such tools avoid these kinds of warts. But I can certainly see the motivation for putting that off until the next stage.

The line you're quoting is literally not Python syntax. Python continues to regard everything after the # as a comment containing arbitrary text.


Copyright © 2014, Eklektix, Inc.
This article may be redistributed under the terms of the Creative Commons CC BY-SA 4.0 license
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds