Python: Creating a Class with Dynamic Set of Members

When defining a class in C++, the only way to vary set of it's members is to use conditional compilation:

class CMyAwesomeObject {
#ifdef __OPENGL
    void bind(void) const {
        // ...
    }
#endif
   // ...

}; // an annoying semicolon

But Python is a dynamic language, and we can modify classes on-the-fly, e. g. add new methods:

class A:
  pass

A.mymethod = lambda self: self.something
A.mymethod.__name__ = "mymethod" # otherwise `print A.mymethod`
                                 # would output smth like
                                 # `<unbound method A.<lambda>>`

But there is also a way to control class members being defined right in the definition of a class.

For example, you do positively can write something like this:

class myAwesomeObject:
  if locale == "en-GB":
    def getColour(self):
      return self.RGB
  else:
    def getColor(self):
      return self.RGB

The fact is that Python class definition body has the same nature as function defintion body. Actually, defining class in a common way:

class MyClass(MyInterface, MyAncestor):
  # ... (class members: functions, constants, etc.)

is equal to the following code:

def __temp_func():
  # ... (class members: functions, constans, etc).
  return type("MyClass", [MyInterface, MyAncestor], locals())
MyClass = __temp_func()
del __temp_func

Yes, it is that simple. It just takes all defined locals and makes them members of your class. And everything you can do to locals can be done to class members. E. g., you can use del statement:

class A:
  def method(self):
    pass
  del method
A().method # AttributeError: A instance has no attribute 'method'

Or add thousands of members in a loop:

class A:
  def methodfabric(i):
    return lambda self: i * i
  for i in range(1000):
    locals()['method%d' % i] = methodfabric(i)
  del methodfabric

A().method577() # 332929

 When should you use this? Well, I don't know. It is just awesome.