classification
Title: No conversion specifier in the string, no __getitem__ method in the right hand value
Type: Stage:
Components: Versions: Python 3.1, Python 3.0, Python 2.7, Python 2.6
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: amaury.forgeotdarc, loewis, msaghaei (3)
Priority: Keywords

Created on 2009-07-01 16:14 by msaghaei, last changed 2009-07-02 12:23 by amaury.forgeotdarc.

Messages (4)
msg89987 - (view) Author: Mahmoud (msaghaei) Date: 2009-07-01 16:14
When using a class instance as a mapping for the right hand value in a
sting format expression without conversion specifier, it seems logical
that the class has a __getitem__ method. Therefore following format
expression should raise an exception.

>>> class AClass(object):
...   pass
... 
>>> c = AClass()
>>> "a string with no conversion specifier" % c
'a string with no conversion specifier'
msg90000 - (view) Author: Martin v. Löwis (loewis) Date: 2009-07-02 06:00
No, it's not logical that there should be an exception. The result looks
right to me.

You are incorrectly assuming that it would always invoke __getitem__ in
this case, which is not true:

py> "a string with a single placeholder: %s" % c
'a string with a single placeholder: <__main__.AClass object at 0xb7d3b1ec>'

So whether it requires c to be a dictionary depends on whether there are
any %(foo)s conversions in the string. With no conversion specifiers,
the values passed to % are irrelevant.
msg90008 - (view) Author: Amaury Forgeot d'Arc (amaury.forgeotdarc) Date: 2009-07-02 11:43
If A is a simple class (old or new style):
   class A: pass

Why is there a difference between:
   "" % object()
and
   "" % A()
?
msg90009 - (view) Author: Amaury Forgeot d'Arc (amaury.forgeotdarc) Date: 2009-07-02 12:23
IMO, the *_FromFormat functions are wrong to decide whether the args
object is a mapping. the code is:
    if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
        !PyObject_TypeCheck(args, &PyBaseString_Type))
        dict = args;

But heap types always fill tp_as_mapping: it points to
PyHeapTypeObject.as_mapping, whose members may be NULL...
PyMapping_Check() would be more appropriate.
History
Date User Action Args
2009-07-02 12:23:29amaury.forgeotdarcsetstatus: closed -> open
resolution: invalid ->
messages: + msg90009
2009-07-02 11:43:33amaury.forgeotdarcsetnosy: + amaury.forgeotdarc
messages: + msg90008
2009-07-02 06:00:43loewissetstatus: open -> closed

nosy: + loewis
messages: + msg90000

resolution: invalid
2009-07-01 16:14:04msaghaeicreate