Skip to content

Instantly share code, notes, and snippets.

@ttsiodras
Created July 9, 2016 15:57
Show Gist options
  • Save ttsiodras/ec5f5a46b3ebb2fa19862304e21d2ef1 to your computer and use it in GitHub Desktop.
Save ttsiodras/ec5f5a46b3ebb2fa19862304e21d2ef1 to your computer and use it in GitHub Desktop.
Annotating Python code with types for mypy

Annotating my python code with type annotations (for the magnificent mypy), I had to do stuff like this:

find . -type f -iname \*A_mapper.py | while read ANS ; do
    cat "$ANS" | \
        sed 's/def OnBasic(\([^,:]*\), \([^,:]*\), \([^,:]*\)):$/def OnBasic(\1: str, \2: AsnBasicNode, \3: AST_Leaftypes) -> None:/' | \
        sed 's/def OnChoice(\([^,:]*\), \([^,:]*\), \([^,:]*\)):$/def OnChoice(\1: str, \2: AsnChoice, \3: AST_Leaftypes) -> None:/' | \
        sed 's/def OnSequence(\([^,:]*\), \([^,:]*\), \([^,:]*\)):$/def OnSequence(\1: str, \2: AsnSequenceOrSet, \3: AST_Leaftypes) -> None:/' | \
        sed 's/def OnSet(\([^,:]*\), \([^,:]*\), \([^,:]*\)):$/def OnSet(\1: str, \2: AsnSequenceOrSet, \3: AST_Leaftypes) -> None:/' | \
        sed 's/def OnSequenceOf(\([^,:]*\), \([^,:]*\), \([^,:]*\)):$/def OnSequenceOf(\1: str, \2: AsnSequenceOrSetOf, \3: AST_Leaftypes) -> None:/' | \
        sed 's/def OnSetOf(\([^,:]*\), \([^,:]*\), \([^,:]*\)):$/def OnSetOf(\1: str, \2: AsnSequenceOrSetOf, \3: AST_Leaftypes) -> None:/' | \
        sed 's/def OnEnumerated(\([^,:]*\), \([^,:]*\), \([^,:]*\)):$/def OnEnumerated(\1: str, \2: AsnEnumerated, \3: AST_Leaftypes) -> None:/' \
        > /tmp/foo && mv /tmp/foo "$ANS"
done

Fun! (for various definitions of "fun").

On a more serious note - worth it. Found many bugs after I annotated with types.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment