Questions about nested for's vs map

Greg Ewing greg.ewing at compaq.com
Thu Oct 28 04:03:35 EDT 1999


Felix Thibault wrote:
> 
> Is it generally considered better not to generate code? (I don't have any
> computer science background, and I'm trying to learn on my own, so I'm a
> little paranoid about learning to program the wrong way.)

Usually it's both more efficient and easier for others
to understand if you can write a procedure which does
something directly, rather than generating code which
is then compiled and executed to do it.

It was fashionable for a while to use techniques like
this in languages such as Lisp, where the boundary
between code and data was very thin. But nowadays it's
generally considered bad style to use it unless there
is really no alternative. In the vast majority of cases, 
there is an alternative, and finding it will make
your code run faster and look nicer.

>                     def makedict(*keys):
>                         depth=len(keys)
>                         keyz = tuple(map(repr, keys))
>                         dict = eval( ('{ %s:'*depth+'None'+'}'*depth) % keyz)
>                         return dict

Recursion is your friend in cases like that. Whenever
you find yourself wanting to build some sort of
hierarchical structure whose depth you don't know
in advance, think recursion!

Greg




More information about the Python-list mailing list