


With annotations, our code is "specific" by default and we work hard to make it generic. Possibly overly so, so we need to do some pre-flight checks. Without type annotations, our code is generic right-off the bat. I couldn't find the type name for any object that can be cast to a str so I put ? for now. But is it even truly generic? In other languages we'd use interfaces or abstract types and inheritance to make functions generic. Let's have a look:ĭef serialize_foo_on_instance ( instance : Union, filename : Union, content : Foo, ** kwargs : Any ): if type ( instance ) = str : instance = Bar.
#Python type annotations generator
Let's assume that instance is an object obtained from a string ID, and that we'd really like to use some kind of string generator for filename. This transpires through the entire language, including the function definitions.īy clamping down on types, are we making our code less reusable? Possibly, let's experiment.
#Python type annotations software
Ages ago I wrote a software forge for Bazaar just by reusing modules from Bazaar itself even though they were never intented to be used that way. Every file you write is a module and can be reused for any purpose. Python is magnificent by how reusable it is. In the same way, Optional doesn't give us a clue about what happens when the value is None. We've introduced docstrings for both our definitions, and they explain what the function does, the role of the parameters, what happens to optional ones and what the values of bool in the return means.Ĭould we do away with the docstring and solely rely on "self-documentation" through type annotations? Not a chance: -> bool doesn't say anything about what it means to receive either True or False. Right so we're a bit more verbose and specified the types each parameters take. :returns bool: True on success, False on error :content Optional: foo data, just creates the file if None :instance Bar: instance to serialize the foo on Takes a foo data, serializes it and saves it as ``filename`` on Serializes foo on a specific instance of bar. Def serialize_foo_on_instance ( instance : Bar, filename : str, content : Optional, ** kwargs : Any ) -> bool : """
