using names before they're defined

Nick Vatamaniuc vatamane at gmail.com
Sat Jul 22 17:10:05 EDT 2006


Dave,

Sometimes generating classes from .ini or XML files is not the best
way. You are just translating one language into another and are making
bigger headaches for your self. It is certainly cool and bragable to
say that "my classes get generated on the fly from XML" but  Python is
terse and reasonable enough to just write it in Python. In other words
instead of saying <turbine> <power>2MW</power></turbine> just write
some Python code that instantiates a turbine  with a 2MW power based on
your class. Then you can evaluate Python code in Python and you even
got your on-the-fly generation.
As a general rule, I would say to think 3 times before touching XML in
Python unless you are absolutely forced to. Config .ini files can be
more acceptable but Python is still best. Why write
;;My turbine class
[turbine]
power=2MW
speed=800rpm
...
when you can just say:
#my turbine class
t=Turbine( power="2MW", \
               speed="800rpm", \
               ...
First case is a little shorter but then you have to use a parser for it
while in the second case you just execute the file, and besides, you
can edit it with any Python editor.

Hope this helps,
Nick V.


davehowey at f2s.com wrote:
> Hi
>
> > 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=
> >
>
> yes, I like the idea of using .ini type file format or XML, very much.
> There are parser available which will automatically building python
> objects from this, won't they (like configparser)? I'll have to get
> reading over the weekend...
>
> > >>def get_class_by_name(name):
> > >>  return globals()[name]
> > >
> >
> > Q&D way to retrieve the class object (Python's classes are themselves
> > objects) known by it's name (as a string).
>
> ok, so it actually returns the class object itself.
> One thing that confuses me is that objects have a name (self.name) but
> object instances also have a name (e.g. myspecialturbine = turbine(...)
> ---- how do I discover the name 'myspecialturbine' ?). And object
> instances have a class name too ('turbine'). Aaargh, too many names!
> what if just want to know what the name of the instance is (in this
> case 'myspecialturbine'?)
>
> Right. I'll have a go at pulling all this together over the weekend
> hopefully. Hurrah! Thanks for all the help, to everyone.
> Dave




More information about the Python-list mailing list