There is nothing in Python 100% equivalent to macro in C.
But there is a makeshift using exec().
Say we want to compute the addition and multiplication of all the elements of a 4-D matrix.
Normally we can define the functions like
import numpy as np
def Addition(matrix):
result=0
for i in range(matrix.shape[0]):
for j in range(matrix.shape[1]):
for k in range(matrix.shape[2]):
for l in range(matrix.shape[3]):
result+=matrix[i,j,k,l]
return result
def Multiplication(matrix):
result=1
for i in range(matrix.shape[0]):
for j in range(matrix.shape[1]):
for k in range(matrix.shape[2]):
for l in range(matrix.shape[3]):
result*=matrix[i,j,k,l]
return result
The 4-fold loop appears twice but I want it to appear only once for conciseness.
In C/C++, we would replace it with a macro like
#define Loop\
for (i=0;i<imax;i++)\
for (j=0;j<jmax;j++)\
........
In Python, we can use exec() instead.
This function takes in a string and execute it as a command.
So the codes become
import numpy as np
string='''
for i in range(matrix.shape[0]):
for j in range(matrix.shape[1]):
for k in range(matrix.shape[2]):
for l in range(matrix.shape[3]):
__replacement__
'''
def Addition(matrix):
result=np.zeros([1])
exec(string.replace("__replacement__","result[0]+=matrix[i,j,k,l]"))
return result[0]
def Multiplication(matrix):
result=np.zeros([1])+1
exec(string.replace("__replacement__","result[0]*=matrix[i,j,k,l]"))
return result[0]
Here, the 4-fold loop appears only once as a global string variable.
BUT BE WARNED.
There is one problem:
The result must be a np.array.
If you initialize result as an ordinary float like result=0. and result=1., the exec() function will not change it and the initial values 0 and 1 will be returned in the end.
This is probably a problem with the difference between reference and value.
Besides, I don't expect any performance gain from this replacement.
The only advantage is convenience in coding replicated commands, which may be useful in some scenarios.
cppin most POSIX-like systems. There are of course many other preprocessors available, M4 being the most notable these days. There are also other C-like preprocessors if you just search a little. However, most Python programmers would frown at you and your code if you used a preprocessor and macros like that. Most C programmers as well actually.