gpt4 book ai didi

python - python 中的 perl 风格函数模板

转载 作者:行者123 更新时间:2023-12-05 01:23:33 25 4
gpt4 key购买 nike

我是 pythonizer 的作者我正在尝试将 perl 样式的函数模板转换为 python。当我生成我认为是等效的代码时,循环变量的值是最后一个值,而不是函数模板出现时的值。关于捕获正确循环变量值的代码的任何想法?例如:

# test function templates per the perlref documentation
use Carp::Assert;

sub _colors {
return qw(red blue green yellow orange purple white black);
}

for my $name (_colors()) {
no strict 'refs';
*$name = sub { "<FONT COLOR='$name'>@_</FONT>" };
}

assert(red("careful") eq "<FONT COLOR='red'>careful</FONT>");
assert(green("light") eq "<FONT COLOR='green'>light</FONT>");

print "$0 - test passed!\n";

翻译成:

#!/usr/bin/env python3
# Generated by "pythonizer -v0 test_function_templates.pl" v0.978 run by snoopyjc on Thu May 19 10:49:12 2022
# Implied pythonizer options: -m
# test function templates per the perlref documentation
import builtins, perllib, sys

_str = lambda s: "" if s is None else str(s)
perllib.init_package("main")
# SKIPPED: use Carp::Assert;


def _colors(*_args):
return "red blue green yellow orange purple white black".split()


_args = perllib.Array()
builtins.__PACKAGE__ = "main"
for name in _colors():
pass # SKIPPED: no strict 'refs';

def _f10(*_args):
#nonlocal name
return f"<FONT COLOR='{name}'>{perllib.LIST_SEPARATOR.join(map(_str,_args))}</FONT>"

globals()[name] = _f10


print(red("careful"))
assert _str(red("careful")) == "<FONT COLOR='red'>careful</FONT>"
assert _str(green("light")) == "<FONT COLOR='green'>light</FONT>"

perllib.perl_print(f"{sys.argv[0]} - test passed!")

(我注释掉了 nonlocal,因为 python 提示这是一个语法错误,并添加了 print 语句)。添加的 print语句写出 <FONT COLOR='black'>careful</FONT>而不是正确的 <FONT COLOR='red'>careful</FONT>

我如何让它捕获 red函数 red 时循环计数器的值是生成的吗?

最佳答案

函数 _f10 没有正确绑定(bind)参数 name

因此函数中使用的name取决于最后一个结果循环。 name 在循环运行时处于全局范围内,因此您仍会得到结果,只是不是预期的那样。

您应该将名称​​绑定(bind)到函数中,方法是向其添加name 参数并部分解析该函数​​,如下所示:

from functools import partial

def _f10(name, *_args):
#nonlocal name
return f"<FONT COLOR='{name}'>{perllib.LIST_SEPARATOR.join(map(_str,_args))}</FONT>"

globals()[name] = partial(_f10, name)

所以每个全局绑定(bind)到一个稍微不同的函数(绑定(bind)第一个参数)。

⇒ 从 perl 代码中找到要绑定(bind)到函数中的标识符可能很困难……您仍然可以尝试以某种方式使用 locals() 绑定(bind)所有局部变量,但这有点困难棘手。

关于python - python 中的 perl 风格函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72307337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com