Skip to content

Instantly share code, notes, and snippets.

@necaris
Created May 31, 2020 12:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save necaris/8943df5f935cd396f5399a24e333a8a0 to your computer and use it in GitHub Desktop.
Save necaris/8943df5f935cd396f5399a24e333a8a0 to your computer and use it in GitHub Desktop.
import typing
def obvious_annotated_error(i: int):
"""Contains a type error which should be very easy to catch."""
return "Hello, " + i
def _innocuous_helper(s):
"""Split a string on whitespace. Perfectly innocent."""
return s.split()
def unannotated_error(i):
"""
Call _innocuous_helper with the wrong type of argument -- will it be caught?
"""
return _innocuous_helper(int(i))
def _ambiguous_returning_helper(greetings: typing.List[str]):
"""
Return "hi" if it's found in the list of greetings, otherwise return None.
Can you see the error that might result?
"""
found = None
for g in greetings:
if g == "hi":
found = g
return found
def less_obvious_error(words):
"""
Call _ambiguous_returning_helper with what we think is the right type...
but is it?
"""
words += ["hello", "g'day"]
return _ambiguous_returning_helper(words).upper()
class AllKindsOfDynamic:
"""
Call an optional function (or list of functions) on an input, in series.
Typical of highly dynamic code I've seen in several Python projects. Can
the typechecker handle this?
"""
def __init__(self, callbacks=None):
if callable(callbacks):
callbacks = [callbacks]
self.callbacks = callbacks or []
def __call__(self, value):
# reveal_type(self.callbacks)
for cb in self.callbacks:
yield cb(value)
if __name__ == "__main__":
executor = AllKindsOfDynamic(lambda v: not v)
print([result for result in executor("foo")])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment