macros - 如何将 julia 字符串宏与变量一起使用?

标签 macros julia

如果这个问题已经得到解答,我深表歉意,但是当我向 PyCall 库提供一个表示字符串而不是简单字符串的变量时,使用 PyCall 库中包含的“py”字符串宏时遇到了令人惊讶的困难。

示例:

@py_str "2 + 2" 

返回4

z = "2 + 2"
@py_str z

导致 interpolate_pycode 不采用 Expr 参数的错误,@py_str ($(z)) 也是如此。

如何向 @py_str 传递字符串变量?

(只是为了澄清 - 上面是一个玩具示例,我将其用于确实需要的应用程序)。

最佳答案

@py_str "\$\$z" 是你的 friend (在 REPL 中使用 ?@py_str 查看宏帮助)。最好编写与 py"$$z"

相同的宏

来自 REPL 帮助(粗体相关部分):

py".....python code....."

Evaluate the given Python code string in the main Python module.

If the string is a single line (no newlines), then the Python expression is evaluated and the result is returned. If the string is
multiple lines (contains a newline), then the Python code is compiled and evaluated in the main Python module and nothing is returned.

If the o option is appended to the string, as in py"..."o, then the return value is an unconverted PyObject; otherwise, it is
automatically converted to a native Julia type if possible.

Any $var or $(expr) expressions that appear in the Python code (except in comments or string literals) are evaluated in Julia and passed to Python via auto-generated global variables. This allows you to "interpolate" Julia values into Python code.

Similarly, ny $$var or $$(expr) expressions in the Python code are evaluated in Julia, converted to strings via string, and are pasted
into the Python code. This allows you to evaluate code where the code itself is generated by a Julia expression.

PS 小拼写错误 ny 而不是 any 位于包源代码中。

关于macros - 如何将 julia 字符串宏与变量一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45405136/

相关文章:

objective-c - 复杂的预处理器宏

c - 将标识符和类型传递给宏

c - 强制宏在 2 个标记之间放置一个空格

printf - 如何指定在 julia 中打印 float 数组的格式?

julia - Julia 中的左右特征向量

c++ - 为什么 token 连接在 C++ 中不起作用?

macros - 调用函数的宏在解释器中有效,在编译器中失败(SBCL + CMUCL)

vectorization - Julia 何时支持向量化?

iterator - 在 Julia 中如何巧妙地处理零维度和迭代器

enums - 模块中的枚举