using names before they're defined

Bruno Desthuilliers onurb at xiludom.gro
Thu Jul 20 08:08:04 EDT 2006


davehowey at f2s.com wrote:
(snip)
> brings me onto another question that has been bugging me, which is, if
> I want to create components (as object instances) at run time (rather
> than through a python code imported in), how do I do this? i.e. if I
> hardcoded something like
> turbine1 = turbine(...)
> then python knows that turbine1 is a turbine. but if I had say some
> kind of user interface and I want to create turbine1 (or suchlike) on
> the fly, how do I actually do that? how do I create objects after run
> time?

Q&D possible solution, no error handling, etc
...just so you get an idea

# schema generated by a GUI
# or directly written in a .py config file
# or whatever

schema = {'turbine1': {'class': 'Turbine',
                       'upstream' : ('frobnicator2',),
                       'downstream' : () # nothing,
                       },
          'frobnicator2' : {'class' : 'Frobnicator',
                            'upstream' : (),
                            'downstream' : ('frobnicator2',),
                           },
         }

# code:

def get_class_by_name(name):
  return globals()[name]

def chain_from_schema(schema):
  objects = {}
  for name, desc in schema:
     klass =  get_class_by_name(desc['class'])
     objects[name] = klass()
  for name, desc in schema:
    target = objects[name]
    ups = [objects[upname] for upname in desc['upstream']]
    downs = [objects[downname] for downname in desc['downstream']]
    target.links(upstream=ups, downstream=downs)
  return objects


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list