Main Content

Dynamic code - Python

Archive - Originally posted on "The Horse's Mouth" - 2008-11-11 23:11:41 - Graham Ellis

When I learned to program, named blocks of code (subroutines and functions) were built into each program and weren't things you could change at run time. But these days, in some languages like Python it's very different and you can write code that includes dynamic functions and methods - after all, in Python everything is an objects (including code) and you can change objects as your program runs.

What does this mean?

Well - here's a piece of valid code:

if kids < 3:
  def more(current):
    return current + 3
else:
  def more(current):
    return current + 8


and in that code I've defined a function in two different ways depending on the value of a variable. I can also redefine it later on in my code if I wish - you can see that in a full example here.

Is this capability a good idea? First comment - be careful how you use it, as it's open to abuse. BUT, yes, it can be very effective. For example, a complete application such as Plone can have default functions defined and they a user-supplied piece of code can replace a named function - a really useful, practical, and powerful facility.