Kir Chou Kir Chou - 1 year ago 102
Python Question

Forced assign value to function call

I know that the buildin function can be replaced by this way.

>>> import os
>>> print(os.system)
<built-in function system>

>>> os.system = "a"
>>> print(os.system)

For some reason, I can not write
in source code directly. Then I tried
. But it doesn't work.

>>> import os
>>> print(getattr(os, "system"))
<built-in function system>

>>> getattr(os, "system") = "a"
File "<stdin>", line 1
SyntaxError: can't assign to function call

Is that possible to achieve this?

Answer Source

getattr only gets an attribute. Besides that, the error indicates that a function call is not a valid assignment target.

What you want is setattr:

>>> import os
>>> os_system = os.system
>>> setattr(os, 'system', 'a')
>>> getattr(os, 'system')
>>> setattr(os, 'system', os_system)
>>> getattr(os, 'system')
<built-in function system>

I do hope you have a good reason for doing this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download