Create a set of objects when their type is set by ini file (Python)
Question: I'm working on a smart home project. I've got a bunch of pieces, such as a
handful of XBee readios, leds, GPS-synched clocks, water counters etc. I tried
to use OOP approach, so I created many classes and subclasses. Now all you
have to do in code is to define hardware, connect it by class-built-in
function to a parent and enjoy. To get an idea:

    
    
    coordinator = XBee24ZBCoordinator('/dev/ttyS1', 115200,
        "\x00\x13\xA2\x00\x40\x53\x56\x23", 'coord')
    spalnya = XBee24ZBRemote('\x00\x13\xA2\x00\x40\x54\x1D\x12', 'spalnya')
    spalnya.connectToCoordinator(coordinator)
    vannaya = XBee24ZBRemote('\x00\x13\xA2\x00\x40\x54\x1D\x17', 'vannaya')    
    vannaya.connectToCoordinator(coordinator)
    led = LED()
    led.connectTo(spalnya.getPin('DO4'), 'DO')
    led.on()
    led.off()
    

I, however, don't want to do that in code. I want to have an ini file that
will define the topology of this 'network'. Thus I want this file to be
readable and editable by a human. Logical choise is ini (against e.j. json as
json when it comes to manual editing of config files is not super friendly to
at least me). Now, I got:

    
    
    [xbee-coordinator]
    type = XBee24ZBCoordinator
    name = coord
    comport = COM4
    comspeed = 115200
    

I can create a function BuildNetwork('my.ini'), that will read and create the
required object instances and connections between them. How do I do it?
There's a class XBee24ZBCoordinator, but whar I get from ini is just a
string...


Answer: You have two options:

  * Define all these classes in a module. Modules are just objects, so you can use `getattr()` on them:
    
        import types
    
    instance = getattr(types, typename)(arguments)
    

  * Store them all in a dictionary and look them up by name; you don't have to type out the name in a string, the class has a `__name__` attribute you can re-use:
    
        types = {}
    
    class XBee24ZBCoordinator():
        # class definition
    
    types[XBee24ZBCoordinator.__name__] = XBee24ZBCoordinator
    

If these are defined in the 'current' module, the `globals()` function returns
a dictionary too, so `globals()['XBee24ZBCoordinator']` is a reference to the
class definition as well.

