简体   繁体   中英

Python: What happens when I modify imported class?

I have written the following code to modify the behavior of a method of one class

import mymodule
mymodule.MyClass.f = mydecorator(mymodule.MyClass.f)
mymodule.MyClass.f(x) # call the modified function

This works for my purposes, but: what have I modified exactly? Is mymodule.MyClass a copy of the original class living inside the current module? Does it in any way affect the original class? How does import work exactly?

When you modify imported module, you modify the cached instance. Thus your changes will affect all other modules, which import the modified module.

https://docs.python.org/3/reference/import.html#the-module-cache

UPDATE:

You can test it.

change_sys.py:

import sys

# Let's change a module
sys.t = 3

main.py:

# the order of imported modules doesn't meter
# they both use cached sys
import sys
import change_sys

print(sys.t)

Output for python ./main.py :

3

It depends. In normal uses cases everything should be ok. But one can imagine special cases where it can lead to weird results:

a.py:

import c

x = c.C()

def disp():
    return x.foo()

b.py:

import c

def change():
    c.C.foo = (lambda self: "bar at " + str(self))

c.py:

class C:
    def foo(self):
        return "foo at " + str(self)

Now in top level script (or interactive interpretor) I write:

import a
import b
a.disp()
b.change()
a.disp()

Output will be:

'foo at <c.C object at 0x0000013E4A65D080>'
'bar at <c.C object at 0x0000013E4A65D080>'

It may be what you want, but the change has been done in b module and it does affect a module.

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