Skip to content

Instantly share code, notes, and snippets.

@benburrill
Created November 15, 2015 05:12
Show Gist options
  • Select an option

  • Save benburrill/e0e2870cc889cb56b3fc to your computer and use it in GitHub Desktop.

Select an option

Save benburrill/e0e2870cc889cb56b3fc to your computer and use it in GitHub Desktop.
Function formatting in Python - see usage
# This is more of an idea than a actual module - although you can use it as such.
# A few things you could do:
# - split the fmt_spec into comma-separated arguments which can be passed into the function
# - make a format method part of the class itself instead of splatting the object into format
class FormatFuncs(dict):
def register(self, func):
self[func.__name__] = type(func.__name__, (), {
"__format__": lambda self, fmt_spec: func(fmt_spec)
})()
return func
# usage
if __name__ == "__main__":
import random
my_fmt_tools = FormatFuncs()
@my_fmt_tools.register
def rand(fmt_spec):
return random.choice(fmt_spec.split("|"))
@my_fmt_tools.register
def upper(string):
return string.upper()
print("{upper:{desc}}: '{rand:hello|world}'".format(
desc="chooses a random word from the phrase 'hello world'",
**my_fmt_tools
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment