python-c-api

is it possible to overwrite “self” to point to another object inside self.method in python?

走远了吗. 提交于 2020-07-18 20:18:50
问题 class Wrapper(object): def __init__(self, o): # get wrapped object and do something with it self.o = o def fun(self, *args, **kwargs): self = self.o # here want to swap # or some low level C api like # some_assign(self, self.o) # so that it swaps id() mem addr to self.o return self.fun(*args, **kwargs) # and now it's class A class A(object): def fun(self): return 'A.fun' a = A() w = Wrapper(a) print type(w) # wrapper print w.fun() # some operation after which I want to loose Wrapper print a

Should {tp_alloc, tp_dealloc} and {tp_new, tp_free} be considered as pairs?

蓝咒 提交于 2020-07-08 18:32:46
问题 Is it true that whatever is created in tp_alloc should be destroyed in tp_dealloc? And similarly for {tp_new, tp_free}? It looks like an obvious symmetry, but I would be grateful for clarification. My actual use case is this: I have: class OSClass : PyObject {...} class Final : OSClass {...} So the corresponding PyTypeObject pto has: pto->tp_basicsize = sizeof(FinalClass) pto->tp_dealloc = (destructor) [](PyObject* pyob) { PyMem_Free(pyob); }; However the new style class stores the PyObject