简体   繁体   中英

python3 print() in exec()

In python3, when I run

>>> exec("","","")
TypeError: exec() arg 2 must be a dict, not str
>>> exec( "print('Hello')", print("World"), print("!") )
World
!
Hello
>>> type(print("World"))
World
<class 'NoneType'>

I mean in the Python3, the arg2 of exec() expects a dict, but we can still put a print() function which is not a dict. why?

Simple!

It's acceptable because its value is None (it can accept None or a dict), which is the default value for the argument.

In a example, a call such as:

exec("print('Hello')")

Is the same as:

exec("print('Hello')", None, None)

print返回None ,这是可选参数的有效参数。

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