173 points · by ceronman · 11y ago · 117 comments
def greeting(name: str) -> str:
Turns out to be backwards compatible in Python3 before 3.5 (though not Python2, yet another reason, if you actually needed one, to start new stuff in Python3)This was talked about and was there for a while.
https://www.python.org/dev/peps/pep-3107/ [2006!]
These weren't specifically called "type" annotations but I think that was in the back of everyone's mind.
This is one reason. All my personal fun-type projects are in the latest Python, and I have the leeway to update work to this.
I know there are a lot of people who don't like or want this, but coming from a C# background before Python, I really like this feature. (not that I want Python to be more like C#, I just like the safety net and guaranteed documentation.)
EDIT: A gem i found on Reddit: Configure setuptools to install it only if required².
def greeting(name: str): str:
or: def greeting(name: str): str
Using once ":" and then "->" for type declaration is inconsistent. Not to mention that the dash is not always aligned with the tip of the ">" and it looks ugly, not like a real arrow!A lot of third-party libraries cropped up that used them to type-check stuff. Type-checking was a popular enough usage for them it's official now, to help gather people under the same libraries and terminology.
You can still use the annotations for other things, of course – the dictionary is still attached to the function and can be inspected as before – but if nothing else is specified, we can now assume they are type declarations.
They are just arbitrary expressions (though in Python, type names like 'int' or 'str' are themselves objects). They don't do anything by default but are accessible as fields of the function object.
greetings.__annotations__ = {'name': str, 'return': str}
Same exact effect.The syntax isn't the magic sauce, the type checker is.
def (str) greeting((str) name):
Edit: it was just an idea, it would be a bit more C-style syntax; of course backwards compatibility wouldn't be possible. Instead of downvoting would you care to explain?The IntelliJ IDE set is really far better than I understood. IMHO.
#greeting :: (str, int) -> str
def greeting(name, age):
In fact, I wonder why more languages don't adopt this syntax, since it greatly simplifies functions with very large types.Anyway the haskell way, especially with Typeclasses, has to be clearest way to express type constraints for functions I've encountered at least from a code readability standpoint.
#greeting :: str -> int -> str
and this is specifically related to the functional nature of Haskell. `greeting "hello"` now instantly becomes a function with type :: int -> str. So the Haskell syntax is about currying, it's about how the function you wrote is really just a cascade of functions.
Doing something silly like making the "arguments" reside in an artificial tuple would definitely be bad practice in most Haskell cases, and so syntactically looks a bit weird and out of place, like it's shoehorned on just because Python function arguments are not like Haskell arguments.
Since Python is not based on this model of a function, I think it's a lot better to keep the syntax in the actual def statement. Adding the return type annotation at the end is nice.
Most probably, this stuff was added to the signature because there were already natural tools like the inspect library that would provide the immediate hooks for making use of it. But even if the implementation didn't need it to be part of the signature like that, I still think it's better for Python's paradigm.
However there are also cases in Python where you get currying, like decorators. And for complicated types like:
# greeting :: (str -> (str, str), int -> List[str]) -> Dict[str, int -> int]
being able to separate the signature from the declaration certainly makes reading it easier.Just for example, in Python it's extremely common to use default arguments, and in fact a lot of stuff in the typing module exists to make it easier to do something like make an Optional type that can either be `None` or a `str` or something. So whatever type signature you're going to mimic from Haskell, you won't be able to give optional types or default arguments without making it totally un-Haskell. And of course no one is going to go off and change Python to work based on Haskell-like type classes (nor should they).
http://mypy.readthedocs.org/en/latest/type_inference_and_ann...
And specifying the concrete str type goes diametrically against the "don't check against a concrete type, embrace duck typing" mantra that Python programmers are taught early.
Because you would need to extend the base list type to support indexing just for this feature, which is a bit iffy if you ask me. I think you have a point about "don't check against concrete types" though, they should update the docs to suggest using an 'Iterable[type]' over a 'List[type]' unless you really really really want a list.
(author)
the type hinting in Python is just that -- hinting, right?
It's for IDEs like PyCharm to use to generate better docs and to be more intelligent about suggestions when writing code. But what it does NOT do is inform the interpreter/compiler about type information, correct?
I.e., Python3 code with perfectly implemented type hints would only make it easier on the developer, and not the interpreter/compiler, yeah?
http://doc.pypy.org/en/latest/faq.html#would-type-annotation...
At the moment no. But there's nothing to say that it couldn't happen in 3.8 or 3.11 or 4.x, since the groundwork is there now.
[1] https://github.com/williame/obiwan
What I do is I have my test runner look for the PYTHON_TYPECHECK environment variable, and if it's set, it imports and enables Obiwan.
I've caught a few subtle bugs this way.
Are there a any good libraries to turn on/off type checking using if debug as part of the decoration logic? If so then running with -O in production would solve some of the problem with this.
def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:
people are going to get them wrong some of the time. Dumping the checking problem on some IDE, with a very vague specification of what an error is, is not progress. If functions have type specifications, you should not be able to call them with the wrong type, ever. This is the job of the compiler and the run time system, not the IDE.Somebody should stop Python's little tin god before he creates another giant step backwards like the Python 2 to 3 mess.
Having most of the standard library plus large portions of the ecosystem come with these hints will be hugely beneficial for productivity.
And of course, there IS a way to check them. IDEs, linters, etc. - I'm sure if you say that your function returns an instance of User and then you try to return a boolean, they will yell at you. And I expect that the standard library and popular libraries WILL run these tools before releasing a stable version. A 90% percent solution is still a step forward compared to relying on much less reliable human brains at every step.
This assumes you can represent a type specification for the function you are calling, this isn't always possible in a dynamic language with advanced metaprogramming facilities.
Think of it as modularizing the compiler and runtime so that the dials on dynamism can be tuned by the team.
PyCharm already used pretty sophisticated type inference this just helps it. But the real win is being able to run mypy or pytype over a codebase automatically.
Types, Contracts, Properties, Tests are different directions in a tensor field. With Python you can mix and match at your will. This is in _no way_ relatable to the 2-3 mess.
For example, C would have been a much safer language if lint was part of the compiler, instead of being optional.
I can have real static typing if I want it. I can also have dynamic typing if I want that. I can use lambda functions. I have LINQ. I can use ScriptCS or some of the new Roslyn stuff if I want to use it as a scripting language. Unix support is not as great, but they are coming along with that. There's no GIL.
Is there some killer feature for Python that I'm overlooking?
Still on average more concise to express the same idea.
Standard library is a nice mix of function-based vs. class-based solutions where appropriate, rather than forcing OO on you even when it's not the ideal approach.
Cross-platform C# usage is still not even a reality, let alone as good as what Python already has.
In several domains of programming, Python has best-of-breed, and sometimes just flat-out the best, available libraries.
Now that Microsoft is supporting non-Windows with .Net core, C# is more attractive. That said, if I was thinking compiled Python with static typing my mind would go to Go.
Lots of options!
Python use cases are completely different from C# - Python is all about fast iteration and prototyping, REPL, interfacing to native libraries etc.
C# is about static typing and all that it implies.
F# is slightly closer to Python with REPL and type inference but still on the C# side of spectrum.
I sometimes wish that one programming language would work for all of my requirements but I keep needing: scripting languages for quickly getting stuff done; practical languages like Clojure and Java, and type strict languages like Haskell (that I would like to use more, but development takes longer).
Looking ahead a few years, the ideal for me would be a loose scripting language that had awesome static analysis tools. So, for example, I would get the safety of Haskell when hacking in Ruby.
For those of you using vim, emacs, and the standard UNIX editing toolchain, the mypy linter provides command-line support. This blog post from April 2015 describes the first version of mypy that includes support for the official typing library.
http://mypy-lang.blogspot.co.uk/2015/04/mypy-02-released.htm...
Having recently switched, PyCharm really does make larger projects a lot easier to refactor / manage.
Edit: Also, to actually answer your question, this is a relatively new feature so I don't think any of the VIM plugins support it yet. Jedi has had type hinting from doc strings for some time now. I'd imagine they'll update that to use this soon.
http://stackoverflow.com/questions/25588642/pycharm-false-sy...