Kir Chou Kir Chou - 1 month ago 9
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)
a


For some reason, I can not write
os.system
in source code directly. Then I tried
getattr
. 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

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')
'a'
>>> setattr(os, 'system', os_system)
>>> getattr(os, 'system')
<built-in function system>

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