Basically, is there already a built-in or commonly available function that does this:
def rename_attribute(object_, old_attribute_name, new_attribute_name):
setattr(object_, new_attribute_name, getattr(object_, old_attribute_name))
delattr(object_, old_attribute_name)
No, there isn't but you could make it easier playing with the namespace:
def rename_attribute(obj, old_name, new_name):
obj.__dict__[new_name] = obj.__dict__.pop(old_name)
There is no builtin or standard library function doing this. I assume, because:
What you can do is to use the Setter and Getter bult-in python's methods to provide a facade / rename for the original attribute.
For instance: suppose you have an attribute attr
and you want to rename it to new_attr
in order to return or modify attr
when you refer to new_attr
.
class Foo:
def __init__(self, a):
self.attr = a
@property
def new_attr(self):
return self.attr
@new_attr.setter
def new_attr(self, new_value):
self.attr = new_value
When calling the the attribute for its new name, we have:
if __name__ == '__main__':
f = Foo(2)
print('The renamed attribute is', f.new_attr)
f.new_attr = 5
print('The renamed attribute after using setter method is', f.new_attr)
print('The old attribute is', f.attr)
At the output:
'The renamed attribute is 2'
'The renamed attribute after using setter method is 5'
'The old attribute is 5'
Notice that
attr
always still available for its use andnew_attr
always will make reference toattr
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With