简体   繁体   English

使用Python进行正态顺序参数评估

[英]Normal order argument evaluation with Python

Is it possible to change the default behaviour of Python so that arguments passed to the functions gets evaluated only after passing? 是否可以更改Python的默认行为,以便传递给函数的参数仅在传递后才会被评估?

Instead of this: 而不是这个:

(lambda x: x)(str(1))

where string cast is done before passing parameter to the function, I'm thinking this kind of scenario at the end: 在将参数传递给函数之前完成字符串转换的地方,我在最后想到这种情况:

(lambda x: x())((lambda: str(1)))

Now str cast is done after moving parameter to the function due to delay wrapper function. 由于延迟包装函数,现在将参数移动到函数后完成str转换。

I'm not too familiar with AST, but could it be used to delay the evaluation of the function parameters, automatically? 我对AST并不太熟悉,但它可以用来自动延迟功能参数的评估吗?

That is the way to do it, as janky as it is. 这是做到这一点的方式,就像现在一样。 These sorts of constructs (functions which are passed as arguments to other functions) are often called "factory functions" or "factories", which are frequently full functions for when you need to do more than one thing. 这些类型的构造(作为参数传递给其他函数的函数)通常称为“工厂函数”或“工厂”,当您需要执行多个操作时,它们通常是完整的函数。 Sometimes people make them @classmethod s when implementing an alternative constructor for a class (these classmethods are usually given names starting with "from", ie fromIterable() ). 有时人们在为类实现替代构造函数时会使它们成为@classmethod (这些类方法通常以“from”开头,即fromIterable() )。 But if you can use a lambda, simple is better than complex. 但是如果你可以使用lambda,简单就比复杂更好。

Also by the way you're missing a close paren on the second example. 顺便说一句,你在第二个例子中错过了一个关闭的人。

Edit: Looks like you fixed it. 编辑:看起来你修好了。

Also, as for AST - In theory, yes. 此外,至于AST - 理论上,是的。 You can pass an AST to the function eval() and it will evaluate it late. 您可以将AST传递给函数eval() ,它将会延迟评估它。 However you can also pass a string, and creating ASTs by hand is overly complicated. 但是你也可以传递一个字符串,手工创建AST过于复杂。 You don't really want to go into that. 你真的不想进入那个。 Not to mention eval() and exec() deprecated on account of being able to execute arbitrary Python code, so a malicious user could literally segfault the Python intepreter if you call it on user input. 更不用说eval()exec()由于能够执行任意Python代码而被弃用,因此如果您在用户输入上调用它,恶意用户可能会逐字地断言Python解释器。

Bottom line: lambdas are the way to go, as sad as that may be. 底线:lambdas是要走的路,尽管可能很难过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM