Python 3 – abusing annotations

Since my retirement a few years ago my habit of trying out sometimes useless or convoluted ideas has gone up a few notches.

Latest discovery is that `inspect.signature()` passes parameter annotations straight through. With a bit of function decorator hackery, you can get positional/keyword instrumented transformers.

def some_func(always_str:str):
   print(f"always_str is {type(always_str)} with a value of {repr(always_str)}")
always_str is <class 'str'> with a value of "'123'"

another example

def reversed_str(raw):
    if not isinstance(raw, str):
        raw = str(raw)
    return raw[::-1]
def goofy_func(bizarro:reversed_str):
    return bizarro
assert goofy_func("Hello World") == "dlroW olleH"

A working proof of concept

In one of my pet projects, I have a method with a signature like `def process_request(self, action:SomeClass.FromDict)` which takes a dictionary for the `action` parameter and passes that to SomeClass.FromDict which then returns a instance of `SomeClass`.

In another case, when dealing with Twisted in Python3 and that all strings are type `` I used something like the magic_decorator above and a transformer `SafeStr` (ex. def do_something(name:SafeStr)` to ensure that the name parameter is ALWAYS of type str. Anecdotally Python3 blows up if you try to do something like .startswith()`.

Grand scheme I think this is an interesting quirk but if my comments and wording isn’t clear, I would prescribe caution if using this in revenue generating code (or code intended to make you wealthy or at least provide money for pizza & beer).