Skip to content

Best way to associate some data with ObjectProxy? #255

@Trung0246

Description

@Trung0246

Current my implementation works like this:

DATA_DB = weakref.WeakKeyDictionary()

def set_data_db(wrapper_instance, data):
	DATA_DB[id(wrapper_instance)] = data

def get_data_db(wrapper_instance):
	return DATA_DB.get(id(wrapper_instance), None)

class Wrapper(wrapt.ObjectProxy):
	def __init__(self, wrapped, extra_data=None):
		super().__init__(wrapped)
		# Set the initial extra data using the external function
		set_data_db(self, extra_data)

But the moment when Wrapper is Wrapper(123) or some other primitive values, this becomes unusable. I have also attempted to do the following:

class Wrapper(wrapt.ObjectProxy):
	def __init__(self, wrapped, data=None):
		super().__init__(wrapped)
		# Initialize a separate dict for the Wrapper-specific attributes
		self._self_dict = {}
		self._self_dict['_data'] = data

	@property
	def data(self):
		# Access the special member variable from the Wrapper-specific dict
		return self._self_dict['_data']

	@data.setter
	def data(self, value):
		# Set the special member variable in the Wrapper-specific dict
		self._self_dict['_data'] = value

But unsure if it's reliable for the case when self itself have data or _self_dict attribute when looking at Proxy Object Attributes section in the docs.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions