Monday 11 June 2012

Meta-programming in Python

Python gives the programmer a plethora of facilities for the meta-programming, for instance the introspection of objects, modules, and such. Moreover, like many other interpreted languages, it allows the execution of generated code.

Which is cool, obviously, if you like algorithms that manipulate other algorithmic-generated algorithms.

http://xkcd.com/917/
This is definitively my case, for I need to generate, at run-time, some data structures and methods that shall be given as an input to an ODE integrator. As both things must be visible from the calling module I need to put them into the global namespace. Piece of cake:
exec open(PATH).read() in globals()
where PATH points to the program-generated file that contains the data structures and the functions I need. Again, the elegance and conciseness of Python are astonishing: exec command checks the syntax and interprets the content of the file, after having it read with read() method, and all the variables are kept in globals namespace.

One-liner power!