Saturday, September 24, 2016

Python Meta-programming 1: Set the stage by understanding the execution model

Meta programming is not for the faint-hearted. Just kidding... Well, to put simply, it gives you enormous power and flexibility to get things done, which would otherwise be difficult to accomplish, if not impossible, without knowing under the hood features of the language. For easier comprehension, I will break things down and present to you a series of Python Meta-programming posts.

To begin with, this post deliberates the execution model of Python, which is a stepping stone to understand meta programming.

Being an interpreted language, compilation in Python occurs at runtime. Unlike languages like Java, here in Python, the bytecode is created on the fly and stored in the memory itself as code objects of units, generally referred to as code blocks, viz. module, function, and class. For each block, a namespace is created using a dictionary and stored as an attribute of the object called __globals__.

It is important to note that variables in python, similar to Java's aliases, are just names that are bound to objects. Python binds a name to an object when it executes constructs like import statements, function and class definitions, and assignment operations.

Scoping of the names bound in the code blocks occurs at two levels, global and local. The module block defines the global scope or namespace. Whereas, names defined in other blocks are local to the block and any block enclosed within it, except when the enclosed block rebinds the name to another object. A local name can be elevated to global namespace by qualifying it with the global statement.

Knowing this we can now start walking down the meta programming lane, like a monk walking blissfully in the thick forests, and totally not being unaware, pun intended.

No comments:

Post a Comment