Date Tags Python

Okay, I have a confession to make. I've thought long and hard about it, and I've decided that this something I can no longer hide from my friends and work colleagues. Some say that it's no one else's business, but I can't go on leading a double life.

Ladies and gentlemen, for as long as I can remember I have been a supporter of strict type-checking. I've tried to sate my habit by indulging in a little type inference when no one's looking, but it's just not the same as having a compiler scour through your source code and shout 'a-ha!' when it comes across a dodgy assignment.

True, a good programmer will spot these mistakes while he's typing, or later in the unit tests, or later still in the integration test, or perhaps when the system has gone live. The point is, at some point after the fact, the error is sure to be spotted.

But for those of us less than perfect, the best way to prevent these simple snafus from seeing the light of day is to trap them during compilation.

The problem is that dynamic languages are rarely compiled, and as much as I enjoy type-checking, I don't want to see it added to Python or Ruby at the cost of rapid development, conciseness and good clean coding fun.

So what's the answer? Well, the clever people who oversee the Python language reckon they've come up with a fairly decent halfway house. Take a look at the following bit of code.

def greeting(name: str) -> str:
    return 'Hello ' + name

Yes, it's Python, under the new PEP0484 which adds extensions for type checking. The function greeting takes a parameter (name) which is of type str and returns a str.

Though, it's not really type-checking because Python isn't compiled. What you're looking at is type hinting. The 'types' are not part of the Python language; they're a set of annotations that are part of an imported library which will allow for lint-type programs and analyzers to check code for sanity. I'm hoping that PyCharm will support this analysis at development time.

Since this is entirely optional then you cannot call it type-checking. As it says in the PEP, it is just a way a hint to the runtime indicating what the type is supposed to be.

But for a type-checking addict like me, it's close enough.


Comments

comments powered by Disqus