向Python添加宏 [英] Adding Macros to Python
问题描述
无论我在下面的代码中引用MY_MACRO
的何处,我都想在本地调用以下代码 .
I would like to invoke the following code in-situ wherever I refer to MY_MACRO
in my code below.
# MY_MACRO
frameinfo = getframeinfo(currentframe())
msg = 'We are on file ' + frameinfo.filename + ' and line ' + str(frameinfo.lineno)
# Assumes access to namespace and the variables in which `MY_MACRO` is called.
current_state = locals().items()
以下是一些使用MY_MACRO
的代码:
Here is some code that would use MY_MACRO
:
def some_function:
MY_MACRO
def some_other_function:
some_function()
MY_MACRO
class some_class:
def some_method:
MY_MACRO
以防万一:
- 我想要具有此功能的原因之一是因为我想避免在需要的地方重复
MY_MACRO
的代码.简短易行的内容将非常有帮助. - 另一个原因是因为我想在宏中嵌入IPython shell,并且希望访问
locals().items()
中的所有变量(请参见
- One of the reasons why I would like to have this ability is because I would like to avoid repeating the code of
MY_MACRO
wherever I need it. Having something short and easy would be very helpful. - Another reason is because I want to embed an IPython shell wihthin the macro and I would like to have access to all variables in
locals().items()
(see this other question)
在Python中这完全可能吗?使它正常工作的最简单方法是什么?
Is this at all possible in Python? What would be the easiest way to get this to work?
请注意,该宏假定可以访问其调用范围的整个名称空间(即,仅将>代码放在函数中)将无法正常工作).还请注意,如果将MY_MACRO
放在函数中,则lineno
会输出错误的行号.
Please NOTE that the macro assumes access to the entire namespace of the scope in which it's called (i.e. merely placing the code MY_MACRO
in a function would not work). Note also that if I place MY_MACRO
in a function, lineno
would output the wrong line number.
推荐答案
MacroPy 是我的一个项目,它将语法宏引入Python.该项目只有3个星期的时间,但是如果您查看链接,您会看到我们有一个非常酷的演示集,并且您可以肯定地使用它来实现所需的功能.
MacroPy is a project of mine which brings syntactic macros to Python. The project is only 3 weeks old, but if you look at the link, you'll see we have a pretty cool collection of demos, and the functionality you want can definitely be implemented using it.
另一方面,python具有一些非常令人称奇的自省功能,因此我怀疑您也许可以仅使用该功能就可以完成所需的工作.
On the other hand, python has some pretty amazing introspection capabilities, so I suspect you may be able to accomplish what you want purely using that functionality.
这篇关于向Python添加宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!