Skip to content

Instantly share code, notes, and snippets.

@sidchilling
Created April 29, 2013 06:35
Show Gist options
  • Select an option

  • Save sidchilling/5480019 to your computer and use it in GitHub Desktop.

Select an option

Save sidchilling/5480019 to your computer and use it in GitHub Desktop.
Script to show how to return a function from another function
# Script to show how functions can return functions
def get_talk(type = 'shout'):
# We define some functions here on the fly.
def shout(word = 'yes'):
return '%s!' %(word.capitalize())
def whisper(word = 'yes'):
return '%s...' %(word.lower())
# Then we return one of these functions
if type == 'shout':
# Note that while returning a function we are not using (). That will call the
# function instead of returning the function.
return shout
else:
return whisper
# How to use this?
talk = get_talk()
# Call the get_talk() and assign the returned function to a variable "talk".
print talk
# Outputs: <function shout at 0xb75ee534>
# Now we can call the returned function
print talk()
# Outputs: Yes!
# We can also combine the assignment of the returned function and calling it in one go!
print get_talk(type = 'whisper')()
# Outputs: yes...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment