5

I was under the impression python string formatting using .format() would correctly use properties, instead I get the default behaviour of an object being string-formatted:

>>> def get(): return "Blah"
>>> a = property(get)
>>> "{a}!".format(a=a)
'<property object at 0x221df18>!'

Is this the intended behaviour, and if so what's a good way to implement a special behaviour for properties (eg, the above test would return "Blah!" instead)?

3 Answers 3

9

property objects are descriptors. As such, they don't have any special abilities unless accessed through a class.

something like:

class Foo(object):
     @property
     def blah(self):
         return "Cheddar Cheese!"

a = Foo()
print('{a.blah}'.format(a=a))

should work. (You'll see Cheddar Cheese! printed)

Sign up to request clarification or add additional context in comments.

2 Comments

And that's where I got confused, used property() inside a class instead of the property decorator. Thanks!
Also note that properties can only be accessed on instances. See here: stackoverflow.com/a/13867254/884640
1

Yes, this is basically the same as if you just did:

>>> def get(): return "Blah"
>>> a = property(get)
>>> print a

If you want "Blah" just call the function:

>>> def get(): return "Blah"
>>> a = property(get)
>>> "{a}!".format(a=a.fget())

Comments

1

Python properties do interop well with .format(). Consider the following example:

>>> class Example(object):
...     def __init__(self):
...             self._x = 'Blah'
...     def getx(self): return self._x
...     def setx(self, value): self._x = value
...     def delx(self): del self._x
...     x = property(getx,setx,delx, "I'm the 'x' property.")
...
>>>
>>> ex = Example()
>>> ex.x
'Blah'
>>> print(ex.x)
'Blah'
>>> "{x.x}!".format(x=ex)
'Blah!'

I believe your problem stems from your property not being part of a class. How are you actually using properties that they aren't working with .format()?

1 Comment

Note that here format isn't calling your property. Python is calling your property to resolve the object that it is going to pass to format. That's just a nitpick, but it is a little different than '{x.x}'.format(x=ex) where the property's getter gets called inside the format function/method.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.