Consider the Reason to Annotate
Easier to Reado
Static code is “self-documenting.” As one author puts it, “Don’t use a comment when you can use a type annotation.” Comments tend to fly under the update radar and usually go untouched when a bug is fixed. Annotating the type tells the reader, “Hi, I’m a string,” or “Hello, I’m a function that returns a Session object.” All in all, the code is easier to read.
Type annotating helps catch type errors before runtime. Adding type annotation helps the IDE predict the type of variable being written. PyCharm alerts the user when a particular function or method being called expects a tuple, string, or integer, and returns a “whatever” datatype. For example, when using a module written by another team member, and that module has a method called
get_cfg_file(environment), the parameter and return type is unknown to the coder. One might guess that environment is likely a string, but PyCharm doesn’t really know this; and neither does the coder. A better scenario: The get_cfg_file declared the parameter with a key value and type annotation. Such as:
def get_cfg_file(environment:str=None). Then the call would be
get_cfg_file(environment=’prod’). When keyboarding of the variable begins, PyCharm (Visual Studio Code, atom, Sublime Text) or whatever IDE used, expect vim…maybe) will hint that the parameter should be a string.
Now, what does get_cfg_file return? None? A string with the file name? A PurePath file object? By annotating the return type, the IDE and the reader of the module will know that a string is to be returned. Annotating would look like:
def get_cfg_file(environment:str=None)-> str: Knowing the return type will help reduce runtime errors like the object has no such property or method.
Thinking It Through
Another advantage in annotating the code is that it makes the developer think about what is being passed around. One must stop and consider the structure of the class, method, or program. Of course, this may slow down development a little. Dynamic typing does have its perks.
Type annotation is excellent and makes things more readable, but there is no need to be a type annotation zealot.