python - What side effects should one expect when method decorator replaces self? -


i want execute method copy of original self passed while execution.

here code i'm talking about:

def protect_self(func):     copy import copy     functools import wraps     @wraps(func)     def decorated(self, *args, **kwargs):         self_copy = copy(self)         return func(self_copy, *args, **kwargs)     return decorated 

in understanding copy function creates new object of same type , copies __dict__ of old 1 new object (using references, changes actual object instances in __dict__ still affect original object).

does mean can sure decorated method cannot modify __dict__ of original instance?

just make sure: don't need secure sandbox behaviour. purpose have single object instanciated use factory. protected method should possible modify passed self should reseted afterwards.

as op clarified in comment purpose threadsafe, there's obvious issue -- copy.copy isn't threadsafe, in addition issue pointed out, copy.copy makes shallow copy , (while self.__dict__ won't modified) mutable objects can altered. using copy.deepcopy deals (at potentially hefty price in terms of performance) in sense worsens issue of thread-safety (since deep-copying can take longer shallow-copying, risk of race condition occurring grows leaps , bounds -- not i'm in way, shape or form recommending having race conditions occur "only rarely", mind!-).

if have make originally-unsafe methods thread-safe, you'll have bite bullet , use locks (or queue , auxiliary thread serialize operations) -- guess if further need silently ignore methods' attempts alter objects, you'll have deepcopy (why stop @ self -- if methods altering globals, example?!-). seem iffy proposition me.


Comments

Popular posts from this blog

unicode - Are email addresses allowed to contain non-alphanumeric characters? -

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -