Reputation: 7383
I have a repeated piece of code in my python code that I can’t factorize in a function because it analyses the call stack.
from traceback import extract_stack as es, format_list as fl
class Pmf
def __init__(self,...):
if not name: name = fl(es(limit=2))[0].split('\n')[1].strip().split("=")[0].strip()
....
In order to avoid copy pasting this code more than 10 times in my case, I would like to use some kind of macro preprocessor directive as in C++.
I don’t think that python Cython supports this feature but I was wondering if there was a python library or a workaround like a pycharm solution. Thanks.
Upvotes: 0
Views: 596
Reputation: 7789
No Python doesn’t have macros. You can ‘simulate’ them by ‘messing’ with the AST (Abstract Syntax Tree) but it isn’t exactly nice and is overall to be honest. I have never found a need for them - there are other ways to do what you might use macros for.
eg
macro='''
a=1
b=54
c=a+b
d=a-b
s = "hi k".split()
print(c**2+d**2, s)
'''
Output:
exec(macro)
5834 ['hi', 'k']
Upvotes: 1