3 ms·
Python does have plenty of metaprogramming capabilities, they just are more complex to use than a macro system. One simple, but highly limited system is metacla
by jsmith45 3y ago
Python does have plenty of metaprogramming capabilities, they just are more complex to use than a macro system. One simple, but highly limited system is metaclasses. Similarly weak but existing features include creating classes at runtime, and adding new methods to classes at runtime. A far more powerful system is compiling source to AST, which can then be manipulated, and finally compiled to bytecode. This allows arbitrary metaprogramming, but is certainly fairly complex.
One could even use it to implement a macro-like system by coding up a new finder that uses a new SourceFileLoader subclass that overrides the (accidentally undocumented!?) `source_to_code` method. In there, one can compile to ast, transform the ast, and then compile the ast to bytecode. (The method was documented back in 3.4 by way of being documented on a ancestor abstract base class, but that documented ancestor was changed to be static in 3.5, leaving this method seemingly accidentally undocumented.)
For the transform the AST step, one might look for apparent function calls to special macro functions, and instead call those macro methods as AST time passing in the AST of its arguments, receiving back as AST that you place in the tree replacing the function call. There is some trickiness here. For example, it is much easier if the macros are defined in another module so that they can already be compiled, and thus available while importing a module that uses them.
It should also be possible to handle macros defined in the same file by stripping out non-macro function definitions, and non-imports from top level statements, compiling that, and then using the result while processing the whole (unstripped) AST, and then finally compiling the result.
Of course such a system is significantly more complicated than with a lisp, but it is still possible. Its load time performance is also not likely to be especially wonderful, but python is not exactly a performance powerhouse.