Ian Bicking: the old part of his blog

Re: More on Python Metaprogramming

Oooh, nice Python code. I'm really interested in how these techniques develop in the Python community.

There's a third trick you can do with Ruby's metaclasses, but it depends on a block-form lambda.

The following example is inspired by UnrealScript, which is a Java-like game programming language. UnrealScript objects can be in different states, and each state can selectively override methods:

class Monster < Actor
  on :make_noise do

  # "default_" should be a decorator.
  default_state :awake do
    on :drink_warm_milk do |glasses|
      self.state = :asleep if glasses >= 1

  state :asleep do
    on :make_noise do

monster = Monster.new
monster.make_noise # -> "Growl!"
monster.drink_warm_milk 2
monster.make_noise # -> "Snore!"

There's more syntactic clutter here than I'd like, but the code works. The biggest limitation is that Ruby doesn't support default values for block parameters.

Is there an obvious way to approximate this in Python? I suspect there might be something with decorators that would get pretty close.

Comment on More on Python Metaprogramming
by Eric Kidd