Home > OS >  AttributeError: 'instancemethod' object has no attribute 'short_description'
AttributeError: 'instancemethod' object has no attribute 'short_description'

Time:04-04

I try to update an attribute of a method, but fails:

class Activity(object):

    def my_method(self):
        return 'foo'
    my_method.short_description = 'old'
Activity.my_method.short_description = 'new'

Exception:

    Activity.my_method.short_description = 'new'
AttributeError: 'instancemethod' object has no attribute 'short_description'

Is there a way to update my_method.short_description?

This needs to work with Python 2.7. With Python 3.x this exception does not happen.

CodePudding user response:

I found this solution:

import types


class Activity(object):

    def my_method(self):
        return 'foo'

    my_method.short_description = 'old'


# Activity.my_method.short_description = 'new'
# --> Exception

class UpdateableInstanceMethod():
    # Otherwise: 'instancemethod' object has no attribute 'short_description'
    def __init__(self, orig_method, short_description):
        self.orig_method = orig_method
        self.short_description = short_description

    def __call__(self, obj):
        return self.orig_method(obj)


Activity.my_method = types.MethodType(UpdateableInstanceMethod(
    Activity.my_method,
    'new'
), None, Activity)

assert Activity.my_method.short_description == 'new'
assert Activity().my_method.short_description == 'new'

assert Activity().my_method() == 'foo'
print('ok')
  • Related