11 ms·
Python 3.5 type hinting in PyCharm 5
- cdnsteve 11y agoI can see this being very useful in teams. Hell, its even useful for a single developer as a form of future documentation. I generally write code today and think, when I read this in 6 months and have no memory, how can I help my future self? For new code bases I'll be adding this.
- zyxley 11y agoI've been very happy about more interpreted languages adding optional typing for exactly this kind of reason.
- jiaweihli 11y agoFor dynamically typed languages, using a popular type annotation syntax (e.g. rdoc for ruby, closure compiler for javascript) and an IDE (like Intellij) can give you 80% of the benefits of type safety by doing code inspection on-the-fly and warning you when it finds incorrect types. The main downside is no compiler safety net when you try to refactor code.
- pauleveritt 11y agoI'm the author of the article. When I gave a preview of this at the PyRVA meetup, I gave this exact illustration, even using "my future self". So...jinx. :)
- cdnsteve 11y agohaha maybe we're twins!
- ghshephard 11y agoPretty impressive that the syntax: 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)
- ianamartin 11y agoI'm insanely happy that I have a new job that is not stuck on Python 2.x 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.)
- heyalexej 11y agoThe "typing"¹ backport package on pypi claims to be compatible back to 2.7. EDIT: A gem i found on Reddit: Configure setuptools to install it only if required². [1] https://pypi.python.org/pypi/typing https://pypi.python.org/pypi/typing [2] http://stackoverflow.com/a/32643122 http://stackoverflow.com/a/32643122
- jsmeaton 11y agoHow is it backwards compatible? Was there syntax added to the language in preparation?
- ghshephard 11y agoI have no idea how they managed to find something that didn't throw a syntax error, yet looked reasonable. Perhaps someone who followed the process will chime in.
- deleted 11y ago[deleted]
- koenigdavidmj 11y agohttps://www.python.org/dev/peps/pep-3107/ https://www.python.org/dev/peps/pep-3107/ 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.
- Walkman 11y ago
- 2bitencryption 11y agosomething that's always had me a bit confused: 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?
- Siecje 11y agoCorrect.
- kevin_thibedeau 11y agoYou could add a decorator or metaclass that dynamically checks the hints at runtime.
- rspeer 11y agoSo far I've been using Obiwan [1] to check types during testing. It's definitely not something you want to do all the time, because it has a huge runtime cost. [1] https://github.com/williame/obiwan 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.
- techdragon 11y agoThis is a job for the little used -O flag. 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.
- bpicolo 11y agoUntil an interpreter/compiler supports otherwise, anyway ;)
- 11y ago
- themartorana 11y agoRecently stumbled upon IntelliJ using the Go plugin package after a Rubyist friend of mine spoke very highly of RubyMine. I have to say I was incredibly impressed. I looked at it a couple years ago when I was mostly Python and it was ok, but it's really stepped up its game - both feature-wise and visually. The IntelliJ IDE set is really far better than I understood. IMHO.
- mateuszf 11y agoThe things you could do in Go vs in (Python | Ruby) are actually are results of difference between static vs dynamic typing. Yeah, static typing requires more key presses and some thinking, but in the case of tools (navigation, refactoring) it makes a huge difference. Ruby support would be years ahead of what it is now if the tools could understand the types in all cases.
- ZLeviathan 11y agoFinally! without the additional type information, it's almost impossible to do any meaningful refactoring...
- eccstartup 11y agoCan this be fixed? http://stackoverflow.com/questions/25588642/pycharm-false-syntax-error-using-turtle http://stackoverflow.com/questions/25588642/pycharm-false-sy...
- Animats 11y ago"Type hinting" without checking is kind of lame. If you're going to have declarations such as 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.
- gamesbrainiac 11y agoI would have to say that I agree. A friend of mine put it this way, "If you expect me to put specify a type and not enforce it, you're just trolling".
- mixmastamyk 11y agoIt's an optional addition to a dynamic scripting language. Lightweight when you need it, more robust when you need it. Sounds like you are trolling.
- DasIch 11y agoIt's not more robust though. The type hints do absolutely nothing.
- mixmastamyk 11y agoFalse, they provide information to analysis tools, which can prevent errors.
- ubernostrum 11y agoIf there is a tool which statically analyzes your code and reports errors due to type mismatches, does it matter to you whether that tool has the exact literal name "ahead-of-time compiler"?
- douche 11y agoI have fond memories of using Python 8-10 years ago, but looking at it today, I'm not sure I see compelling reasons not to just use C# instead. 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?
- ubernostrum 11y agoStill less boilerplate than C#. 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.
- vpkaihla 11y agoCompared to C#, it doesn't require you to run Windows in production.
- muaddirac 11y agoI think its ubiquity is important (installed by default on most non-Windows machines, at least in my experience) combined with the simplicity of running a python script. 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!
- zurn 11y agoThere's quite some dissonance between the artificial "generics" vs normal types. Why the concrete str type for strings, but not for lists? I realize there are implementation level arguments for it, but the resulting compromise does not seem good. 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.
- orf 11y ago> Why the concrete str type for strings, but not for lists 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.
- arnsholt 11y agoProbably because Python doesn't distinguish characters and strings. When you index into a string, you get a string back (that happens to be length one, of course), which means that a string is a list of strings. Thus, exploding string into a list type isn't really possible as the type of `str` is something like `List[str]`, which doesn't make a whole lot of sense.
- willvarfar 11y agoSee Obiwan. pypi.python.org/pypi/obiwan/ Prettier? (author)
- Klasiaster 11y agoHas someone tried GNOME Builder? I found it quite good for C, but the Python mode of PyCharm is still superior regarding search and introspection, yet it is not Free Software…
- graffitici 11y agoSo how do we get some of these benefits if we don't use PyCharm, but use Vim? Are there standalone tools, or VIM plugins?
- bitdivision 11y agoIf you can deal with a different file navigation setup (and outside a terminal obviously), VIM emulation in PyCharm is very good. 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.
- pixelmonkey 11y agoIt's cool that PyCharm added support for this -- the point of the typing module and the type hinting PEP is for IDEs to adopt it for linting purposes. 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.html http://mypy-lang.blogspot.co.uk/2015/04/mypy-02-released.htm...
- thomasahle 11y agoI wonder why, given they call it 'type hints', they didn't go for Haskell-like type comments: #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.
- jfaucett 11y agoI've wondered this exact same thing myself for other languages. I doubt its a lack of familiarity since I would bet most compiler/language authors are aware of most Haskell concepts/idioms. I think it probably has more to do with function definition semantics in non-functional languages but it seems that could be easily worked around... 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.
- p4wnc6 11y agoI love Haskell, but I'm not sure this would actually be better for Python. To be Haskell-like, the comment would actually be different than what you wrote: #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.
- thomasahle 11y agoI don't think this is a case of shoehorning anything. It is true that in Haskell you use currying more often, while in Python you usually supply a tuple with all the arguments at once. 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.
- mark_l_watson 11y agoI like this. I use Ruby as a scripting language more often than Python and I would be happy to see similar additions to Ruby to improve code readability and IDE support (although RubyMine) does an awesome job of warning of possible code problems just using code inspection). 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.