Today I Learned

hashrocket A Hashrocket project

Annotate Args with Anything

Python annotations don't do anything. Annotations are just meta information about the arguments of your method. You can apply this metadata in any way that you see fit.

Let's check out a function with no annotations:

def talk(a, b, c):
    pass

talk.__annotations__
# {}

Makes sense, an empty dictionary. Now lets say that a should be an str.

def talk(a: str, b, c):
    pass

talk.__annotations__
# {'a': <class 'str'>}

What's unique about python is that its primitive types are objects/classes. This allows for annotations to be accomodating of any object/class.

def talk(a: str, b: 'hi', c):
    pass

talk.__annotations__
{'a': <class 'str'>, 'b': 'hi'}

Any type or instance? What about declaring a variable outside of the method and using that as an annotation.

birds = {'corvids': True}
def talk(a: str, b: 'hi', c: birds):
    pass

talk.__annotations__
# {'a': <class 'str'>, 'b': 'hi', 'c': {'corvids': True}}

Yeah you can do that!! Crzy!!

Check out how argument annotations can be used as a type system with mypy

See More #python TILs