Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a python function to rename an object's attribute?

Tags:

python

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)
like image 362
chappy Avatar asked Aug 14 '14 14:08

chappy


3 Answers

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)
like image 86
enrico.bacis Avatar answered Nov 07 '22 12:11

enrico.bacis


There is no builtin or standard library function doing this. I assume, because:

  • it is trivial, as your completely sufficient example shows
  • there's no general use case
like image 39
knitti Avatar answered Nov 07 '22 10:11

knitti


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 and new_attr always will make reference to attr.

like image 2
Jorge Massih Avatar answered Nov 07 '22 10:11

Jorge Massih