More efficient way to use weakref for an object as a property?

I know in Python, I can do something like the following:

from weakref import ref class A(object): def __init__(self, parent): self._parent = ref(parent) @property def parent(self): return self._parent() a = A(some_other_object) print a.parent 

In this hypothetical situation, I create an instance of A and gain access to the parent object with a weak reference. It seems that 4 lines of code for a loosely coupled property is a bit, but.

I thought I could do something like the following as a shortcut to the above:

 class A(object): def __init__(self, parent): self.parent = property(ref(parent)) 

but this does not return the parent object, it returns the property object. Is there a more compact way to create an object with a low reference that I can access, rather than being called?

+4
source share
2 answers

I am using weakref.proxy for this.

 import weakref class A(object): def __init__(self, parent) self.parent = weakref.proxy(parent) 
+4
source

You can make it a little more compact, but not as compact as you think. The problem is that there are two incompatible needs:

  • The _parent assignment must be inside the method body (for example, __init__ ), because it must be set in the instance.
  • Creating a property cannot be inside the body of the method, because properties only work when defined in the class.

An additional complication is that there is no way to do parent = somePropertyMaker(ref(x)) and the function somePropertyMaker "know" that it is given the name "parent". This means that you will need to explicitly pass the name of the hidden attribute that underlies this property.

With this in mind, you can do this:

 def weakProp(hidden): @property def prop(self): return getattr(self, hidden)() return prop class A(object): def __init__(self, parent): self._parent = ref(parent) parent = weakProp('_parent') class B(object): pass >>> b = B() >>> a = A(b) >>> print b <__main__.B object at 0x00000000029D0470> >>> print a.parent <__main__.B object at 0x00000000029D0470> 

weakProp is a property creator function that retrieves a hidden attribute and calls it to access an object with a low reference.

0
source

Source: https://habr.com/ru/post/1490098/


All Articles