+ 1
Program problem
Explain me code step by step, please: def f(m: str, v:str) -> int: return f._annotations_ print(f('a', 'b')['m']) >>> <class 'str'> >>>
2 Answers
+ 1
Simply put, this is a basic annotation. "What is an annotation?" It is an empty dictionary where we can store function paramenters, arguments and return values for a functions expected inputs. This dunder method essentially accepts key/value pairs for others to use as possible arguments or inputs.The annotations are completely optional, but 3rd party libraries benefit from this standardization as well. Also, annotations are beneficial at establishing "help" arguments and documentation. Another important area to note, is annotations are accessed at compile-time. Lastly, annotations will always return a "return" when a -> is declared. Try this:
def f(m:'this is m',v:'this is v') -> int:
return f.__annotations__
print(f('a', 'b')['m'])
In your example above, the function "f" is created with values "m" and "v", but you can have any values, you are not required to use "m" and "v",but in the example above they represent string types and your "return" is an integer type. When the function is called
0
def f(m:str, v:str) -> int # you can use m: str to append some string metadata to stuff (called annotations) and -> is to give annotations to the returned value.
return f._annotations_ is a function attribute that is a dictionary of all the annotations, so it basically return the annotations of m that is str (that is a classes)