using names before they're defined
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Thu Jul 20 18:04:34 EDT 2006
davehowey at f2s.com a écrit :
> Hiya
>
> Could you just talk me through this... is it:
>
>
>>schema = {'turbine1': {'class': 'Turbine',
>> 'upstream' : ('frobnicator2',),
>> 'downstream' : () # nothing,
>> },
>> 'frobnicator2' : {'class' : 'Frobnicator',
>> 'upstream' : (),
>> 'downstream' : ('frobnicator2',),
>> },
>> }
>>
>
>
> ok, so schema is a dictionary of different components, defining what
> class they are and what they're connected to.
Yeps.
Note that it could as well be a list of tuple or anything like this, ie:
schema = [
('turbine1', 'Turbine', ('frobnicator2',), ()),
('frobnicator2', 'Frobnicator', (), ('frobnicator2',),
]
I choose a dict for readability.
Also, I gave the example using Python code as 'config' format, but any
structured enough text format could do, ie JSON, XML, or even ini-like:
# schema.ini
objects = turbine1, frobnicator2
[turbine1]
class=Turbine
upstream=frobnicator2
downstream=
[frobnicator2]
class=Frobnicator
upstream=
downstream=turbine
Now you just read the file with the standard config parser and build
your chain from it... (implementation left as an exercice...)
>>def get_class_by_name(name):
>> return globals()[name]
>
>
> what does this function do exactly?
Q&D way to retrieve the class object (Python's classes are themselves
objects) known by it's name (as a string).
globals() returns the module's namespace as a dict object with
'name':object pairs. This code assume that the name is available in the
current module's namespace, but could be improved to handle needed
imports etc.
>>def chain_from_schema(schema):
>> objects = {} # so objects is our list of objects ?
>> for name, desc in schema:
# can you step through a dictionary like this?
Nope, sorry, it's a mistake I do over and over. It's of course:;
for name, desc in schema.items():
(note that you can iterate over a dict's keys with 'for k in thedict:' )
>> klass = get_class_by_name(desc['class'])
# does this create an object called klass?
Nope, it binds the class object (retrieved by get_class_by_name()) to
the local name 'klass' ('class' is a reserved name).
>> objects[name] = klass()
>
> sorry for being dim..
Where ?
More information about the Python-list
mailing list