Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
class ProxyStr(str, CoW):
def __init__(self, *args, **kwargs):
# str keeps it's setup all in __new__
CoW.__init__(self, *args, **kwargs)
self._hash_cache = None
def __hash__(self):
if self._hash_cache is None:
self._hash_cache = super().__hash__()
return self._hash_cache
def __copy__(self):
return ProxyStr(self)
class ProxyTuple(ProxyList, CoW):
def __init__(self, tup):
# Turning into a list so we can weakref
return super().__init__(tup)
def __eq__(self, obj):
"""Pretending to be a tuple..."""
return tuple(self) == obj
def __hash__(self):
return super().__hash__()
def __copy__(self):
return ProxyTuple(self)
def __setitem__(self, *args, **kwargs):
raise TypeError("'tuple' object does not support item assignment")
def proxify(value):
"""
Wrap the value in a proxy shell if need be.
Returns the object or the proxy object.
"""
if type(value) is str:
value = ProxyStr(value)
elif type(value) is list:
value = ProxyList(value)
elif type(value) is tuple:
value = ProxyTuple(value)
elif type(value) is set:
value = ProxySet(value)
elif type(value) is dict:
value = ProxyDict(value)
return value
# If only one thing is watching, we don't need to copy
copy_required = False if get_true_reference_count(self) == 1 else True
if copy_required:
# Just-in-time copy
my_copy = copy(self)
my_type = type(my_copy)
else:
my_copy = self
my_type = type(self)
my_old_hash = hash(self)
# HACK: need to figure out a proper sloution for this...
# Tuple __iadd__ (and likely others) causes infinite recursion.
if my_type is ProxyTuple:
my_type = ProxyList
# Proxify the args if we need to
args = [proxify(arg) for arg in args]
kwargs = dict((key, proxify(val)) for key, val in kwargs.items())
# Run this call in-place
ret = getattr(super(my_type, my_copy), method_name)(*args, **kwargs)
# Only bother calling update if we had to copy
if copy_required:
# Call our cb function
for func in self._flyweight_cb_func:
func(my_copy)
else:
# Update the cache with our new value
def __copy__(self):
return ProxyList(self)