Demystifying Python metaprogramming
To metaprogram is to write a program that writes or manipulates itself or another program. It sounds much more intimidating than it is. In fact, metaprogramming has been a large part of two chapters in this book.
We were metaprogramming in Chapter 6, Automating Maya from the Outside, with our use of eval
and exec
to run arbitrary code. The following is an example of metaprogramming using the eval
function. We evaluate a string to sum the numbers from 1 to 5.
>>> s = '+'.join([str(i) for i in range(1, 6)]) >>> s '1+2+3+4+5' >>> eval(s) 15
We were also metaprogramming when creating closures and decorators in Chapter 4, Leveraging Context Managers and Decorators in Maya. The following is an example of metaprogramming using a function to return a different function.
>>> def _make_sort(reverse):
... def dosort(items):
... return sorted(items, reverse=reverse)
... return dosort
>>> sort_ascending = _make_sort...