a problem with writing a generator

Dave Angel davea at ieee.org
Thu Jan 14 16:42:43 CET 2010

PaweB Bany[ wrote:
> Hello,
> Please forgive me if I repeat the subject anyhow. I am trying to write a
> simple program in Python which scans a config file in search for
> "include" lines. If those lines are found, the files included there are
> followed and scanned and if any further "include" lines are found, the
> whole procedure repeats itself. The program ends when the whole tree
> structure of those "includes" is generated.
> I seem to have some blackout in my mind because I cannot understand how
> to use a generator functionality to complete the task. If anybody has
> already done such thing I would be very grateful for any guidance.
> Regards,
> Paweł
If you really want a tree structure, then I don't see why you expect a 
generator to be necessary, or helpful. A generator is frequently a good 
way tor reduce a tree to linear form, so if you were trying to make a 
single set of includes, I'd write a generator. Otherwise, you just need 
a recursive function.

Do you understand recursion? Have you any experience with it in other 
programming languages?

In this case, you write a single function that takes a filename as an 
argument, and returns a list of the includes contained within it. Then, 
inside that function, right after finding such an include, you call the 
same function, passing it the include name, and append the return value 
to your own list.

All the details of building the tree just work, if you get it right.

If you get stuck implementing this outline, then post whatever code you 
have so far, and give the reason why you're stuck. Also, at that point, 
define exactly what you expect the "tree" to look like. There are at 
least a few reasonable choices, and there's no point in heading the 
wrong way.


More information about the Python-list mailing list