Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to unshadow the keyword 'property'?

Tags:

python

I am supporting a legacy python application which has a class written as such (still running in python 2.4):

class MyClass(object):

    def property(self, property_code, default):
        ...

Now I am adding some new code to it:

    def _check_ok(self):
        ...

    ok = property(lamdba self:self._check_ok())

Basically I want to add a property 'ok' to this class.

However it does not work. I encountered this error message:

TypeError: property() takes at least 2 arguments (1 given)

The existing class method 'property' has overshadowed the built-in 'property' keyword.

Is there any way I can use 'property' the way it meant to be in my new code?

Refactor the existing property() function is not an option.

EDIT: If I put the new code before the MyClass::property def, it will work. But I really want to see if there is a better solution

EDIT 2: These codes work in shell

>>> class Jack(object):
...   def property(self, a, b, c):
...      return 2
...   p = __builtins__.property(lambda self: 1)
...
>>> a = Jack()
>>> a.p
1
>>> a.property(1, 2, 3)
2

But the same technique does not work in my app. Got AttributeError: 'dict' object has no attribute 'property' error

like image 665
Anthony Kong Avatar asked Dec 22 '22 19:12

Anthony Kong


2 Answers

Python 2:

import __builtin__
__builtin__.property

Python 3:

import builtins
builtins.property
like image 163
Thomas K Avatar answered Dec 24 '22 07:12

Thomas K


How about this:

__builtins__.property(lamdba self:self._check_ok())
like image 28
jonesy Avatar answered Dec 24 '22 08:12

jonesy