简体   繁体   中英

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?

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.

I'm not too familiar with AST, but could it be used to delay the evaluation of the function parameters, automatically?

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() ). But if you can use a lambda, simple is better than complex.

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. You can pass an AST to the function eval() and it will evaluate it late. However you can also pass a string, and creating ASTs by hand is overly complicated. 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.

Bottom line: lambdas are the way to go, as sad as that may be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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