我正在使用Inline::Python0.56,嘗試使用來自 Perl 的命名引數呼叫 Python 函式。根據要求,我已將原始代碼片段替換為可以運行的示例:
use strict;
use warnings;
use 5.16.3;
use Inline Python => <<'END_OF_PYTHON_CODE';
# Interface
def get_sbom_of_package (
package_name = None,
target_path = None,
):
assert package_name is not None
assert target_path is not None
print ( package_name, target_path )
return package_name
END_OF_PYTHON_CODE
my $package = 'thePackage';
my $target_path = $ENV{HOME};
my $sbp = get_sbom_of_package(
package_name => $package ,
target_path => $target_path
);
say $sbp;
我的錯誤是:
TypeError: get_sbom_of_package() takes from 0 to 2 positional arguments but 8 were given at (eval 3) line 3.
我還需要執行行內 Python 以了解我正在為其提供命名引數嗎?我已將 Perl 中的呼叫替換為
my $sbp = get_sbom_of_package(
$package ,
$target_path
);
它作業得很好。我想要么
- 我的 Python 不好,或者
- 一個 Inline::Python 配置問題
- Inline::Python 限制
從最可能到最不可能排序。:-)
uj5u.com熱心網友回復:
原來它不受支持:https ://rt.cpan.org/Public/Bug/Display.html?id=91360
uj5u.com熱心網友回復:
如果我正確閱讀 XS 并記住我的 Python 擴展模塊的作業,這是不可能的。
Inline::Python似乎呼叫 py callables 使用PyObject_CallObject它傳遞引數元組 - 沒有任何命名/關鍵字引數。
因此,您必須自己做,也許通過在 py 可呼叫物件周圍放置一個包裝器,該包裝器理解您的意思parameter => value, ...并構造正確的元組以傳遞。當然,您還需要冗余地知道默認值。您可能會Inline::Python支持查詢可呼叫的簽名以查找關鍵字 args ......但是您仍然必須自己調整那些適合普通 Perl 子例程呼叫的語意。
uj5u.com熱心網友回復:
Note This was of course meant to be a sketch, the idea being that "named arguments" are implemented via a hash(ref) -> dictionary. By all means add other needed arguments to the list, function names, arrayrefs, whatnot.
The attempted code passes four (4) arguments to Perl's function call,? while Python's function is written to take two (each with a default value).
If you want to pass named parameters to a Python function, one way would be to pass a dictionary. Then this incidentally mimics your Perl use, as well
def adict(d):
for key in d:
print("key:", key, "value:", d[key])
Then your code could go as
use warnings;
use strict;
use feature 'say';
use Inline::Python;
adict( {a => 1, b => 2} );
use Inline Python => <<'END_PY'
def adict(d):
for key in d:
print("key:", key, "value:", d[key])
END_PY
This prints output from the python function.
Or one could devise a system for passing Perl's four arguments and taking them in Python and interpreting them as name => value pairs, but why.
? A function in Perl takes a list of scalars. Period. So this
func(package_name => $package, target_path => $target_path)
or even this
my %ph = (package_name => $package, target_path => $target_path);
func( %ph );
is really this
func('package_name', $package, 'target_path', $target_path)
That "fat comma" (=>) is a comma, whereby its left argument also gets quoted.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/508434.html
下一篇:從perl陣列中提取資料哈希參考
