Python: Non-standard use of dot operator

  • Print

In PHP, there is a special . operator to concatenate strings. Of course, we aren't going to do that in Python; it is sort of weird. Instead of that, let's try to solve a legendary NumPy problem: how to distinguish element-wise array multiplication from matrix-matrix 'row-by-column' multiplication? We already know that the first thing is done like A * B, and the second like, or like weird A @ B construction in Python 3.5 draft. Well, let's see some code:

import inspect

class Matrix(object):
  def __getattr__(self, which):
    frame = inspect.stack()[1][0] # we assume stack is deeper than 1 here
    locals = frame.f_locals
    if which in locals:
      return 'matvec' # return matrix-matrix multiplication result here
      return super(Matrix, self).__getattr__(which)

a = Matrix()
b = Matrix()
print(a.b) # outputs 'matvec'!
print(a.c) # raises AttributeError!

What's going on? An awesome thing about Python is that it gives access to the whole execution stack, including local and global namespaces for each frame. We just take the frame operator . was called from, find an element with the requested name, and 'multiply' our matrix by it. If there is no element with such name, we just return regular attribute.

So, it is just a little smart trick to implement an exotic behavior of dot operator. Enjoy using, if only you are brave enough!

Python is awesome.