4

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

Anthony Kong
  • 37,791
  • 46
  • 172
  • 304
  • You used __builtins__, what happens when you use __builtin__ as Thomas K suggested? – Mike Axiak Jan 07 '11 at 01:40
  • Couldn't you just have `ok = property(_check_ok)`? Or use a decorator (`@property` above the `_check_ok` def)? Depending on your solution, you may have to more fully qualify `property` of course. – detly Jan 07 '11 at 01:42

2 Answers2

10

Python 2:

import __builtin__
__builtin__.property

Python 3:

import builtins
builtins.property
Thomas K
  • 39,200
  • 7
  • 84
  • 86
  • Thanks Thomas, it works. Just do not understand why \_\_builtins\_\_.property in shell works... – Anthony Kong Jan 07 '11 at 01:45
  • 3
    Short version: it's a messy part of Python, as `__builtins__` can be either a dict or a module. See http://stackoverflow.com/questions/1184016/why-builtins-both-module-and-dict and http://stackoverflow.com/questions/2173425/two-conflicting-meanings-of-builtins-in-python-3-python-3-1-python-3k-python30/2173457#2173457 – TryPyPy Jan 07 '11 at 03:13
  • 3
    And in case its relevant to anyone: In Python 3, you do `import builtins` (plural, no underscores), rather than `import __builtin__`. – Thomas K Jan 07 '11 at 11:01
1

How about this:

__builtins__.property(lamdba self:self._check_ok())
jonesy
  • 3,502
  • 17
  • 23
  • Get this error: AttributeError: 'dict' object has no attribute 'property'. But if I tried your in the shell, it works. – Anthony Kong Jan 07 '11 at 01:35
  • sorry - I tested at the prompt. In a script you 'import __builtin__' and do __builtin__.property like Thomas K said. – jonesy Jan 07 '11 at 01:38