C++什么是python等效的宏观预处理器指令?

发布于 2025-02-13 03:37:57 字数 400 浏览 0 评论 0原文

我的Python代码中有一个重复的代码,我无法分解功能,因为它可以分析呼叫堆栈。

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()
        ....

为了避免在我的情况下复制超过10次粘贴此代码,我想使用某种宏观预处理器指令,如C ++。

我认为Python Cython不支持此功能,但我想知道是否有Python库或像Pycharm解决方案这样的解决方法。谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

油饼 2025-02-20 03:37:57

没有Python没有宏。
您可以通过与AST(抽象的语法树)“混乱”来“模拟”它们,但这并不是很好,总的来说是说实话。我从来没有发现他们的需求 - 还有其他方法可以做您可能使用宏的方法。

例如

macro='''
a=1
b=54
c=a+b
d=a-b
s = "hi k".split()
print(c**2+d**2, s)
'''
           

输出:

exec(macro)
5834 ['hi', 'k']

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']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文