This project allows to add a property that is an alias for an indexer to a class.
This decorator adds keyaliases to cls and then returns cls.
This function returns a keyalias decorator for a class.
This function returns a new keyalias property.
import functools
__all__ = [
"classdecorator",
"getdecorator",
"getproperty",
]
def classdecorator(cls, /, **kwargs):
for alias, key in kwargs.items():
pro = getproperty(key)
setattr(cls, alias, pro)
return cls
def getdecorator(**kwargs):
return functools.partial(classdecorator, **kwargs)
def getproperty(key):
def fget(self, /):
return self[key]
def fset(self, value, /):
self[key] = value
def fdel(self, /):
del self[key]
doc = "self[%r]" % key
ans = property(fget, fset, fdel, doc)
return ansfrom keyalias import getdecorator
@getdecorator(six=6)
class MyClass:
def __init__(self):
self.data = list(range(10)) # Example list with 10 elements
def __getitem__(self, index):
return self.data[index]
def __setitem__(self, index, value):
self.data[index] = value
def __delitem__(self, index):
del self.data[index]
# Create an instance of MyClass
my_instance = MyClass()
# Use the alias property to access index 6
print(my_instance.six) # prints 6
my_instance.six = 42
print(my_instance.six) # prints 42
del my_instance.six
print(my_instance.six) # prints 7