Main Content

Dynamic functions and names - Python

Archive - Originally posted on "The Horse's Mouth" - 2006-08-03 06:02:46 - Graham Ellis

In Python, everything is held as an object in a variable - and I do mean everything, even named pieces of code. So that means that you can do some amazing things (or things that would be amazing in other languages) such as set up a named piece of code to perform action "x", the replace it dynamically with a piece of code to perform action "y" or action "z".

# conditional functions

def about():
   return "initial"

try:
   value = int(raw_input("Please enter a number: "))
   if value % 2:
      def about():
         return "that's odd"
   else:
      def about():
         return "that's even"
except StandardError:
   pass

print about()


This piece of code sets up a function called "about" to a default value, then replaces it with two alternative pieces of code if the user enters an odd or even number, leaving it alone if the user doesn't make a valid entry .... so that when the about() function is called, it runs in in one of three different ways ...

earth-wind-and-fire:~/aug06 grahamellis$ python confun
Please enter a number: 5
that's odd
earth-wind-and-fire:~/aug06 grahamellis$ python confun
Please enter a number: 4
that's even
earth-wind-and-fire:~/aug06 grahamellis$ python confun
Please enter a number: ksjksdjkfsdf
initial
earth-wind-and-fire:~/aug06 grahamellis$