Skip to content

Instantly share code, notes, and snippets.

@luisenriquecorona
Created February 25, 2020 21:28
Show Gist options
  • Save luisenriquecorona/52344b2bea47175bbc8b7bb78436df7f to your computer and use it in GitHub Desktop.
Save luisenriquecorona/52344b2bea47175bbc8b7bb78436df7f to your computer and use it in GitHub Desktop.
Function annotations. Python 3 provides syntax to attach metadata to the parameters of a function declaration and its return value.
def clip(text:str, max_len:'int > 0'=80) -> str:
"""Return text clipped at the last space before or after max_len
"""
end = None
if len(text) > max_len:
space_before = text.rfind(' ', 0, max_len)
if space_before >= 0:
end = space_before
else:
space_after = text.rfind(' ', max_len)
if space_after >= 0:
end = space_after
if end is None: # no spaces were found
end = len(text)
return text[:end].rstrip()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment