[Python-Dev] other "magic strings" issues

Martin v. Löwis martin at v.loewis.de
Sat Nov 8 15:51:35 EST 2003


Alex Martelli <aleaxit at yahoo.com> writes:

> Lists are mutable, which makes "creating bound methods" (or the equivalent 
> thereof) absolutely unavoidable -- e.g.:
>     xxx = somelist.somemethod
>     " alter somelist at will "
>     yyy = xxx( <args if needed> )
> 
> xxx needs to be able to refer back to somelist at call time, clearly.

It depends on the source code. In your example, I agree it is
unavoidable. In the much more common case of

yyy = somelist.somemethod(<args if needed>)

one could call the code of somemethod without creating a bound method,
and, in some cases, without creating the argument tuple. It would be
good if, for

>>> def x(a):
...   a.append(1)
...

the code could change from

  2           0 LOAD_FAST                0 (a)
              3 LOAD_ATTR                1 (append)
              6 LOAD_CONST               1 (1)
              9 CALL_FUNCTION            1
             12 POP_TOP
             13 LOAD_CONST               0 (None)
             16 RETURN_VALUE

to

  2           0 LOAD_FAST                0 (a)
              3 LOAD_CONST               2 (append)
              6 LOAD_CONST               1 (1)
              9 CALL_METHOD              1
             12 POP_TOP
             13 LOAD_CONST               0 (None)
             16 RETURN_VALUE

where CALL_METHOD would read the method name from
stack. Unfortunately, that would be a semantical change, a __getattr__
would not be called anymore. Perhaps that can be changed to

  2           0 LOAD_FAST                0 (a)
              3 LOAD_METHOD              1 (append)
              6 LOAD_CONST               1 (1)
              9 CALL_METHOD              1
             12 POP_TOP
             13 LOAD_CONST               0 (None)
             16 RETURN_VALUE

where LOAD_METHOD has the option of returning an fast_method object
(which exists only once per type type and method), and CALL_METHOD
would check for whether there is a fast_method object on stack, and
then explicitly pop "self" from the stack as well.

> Few situations are as favourable as this one -- immutable object, no
> arguments, just two possible constant-returning callables needed. 

Most cases are as favourable as this one. If you immediately call the
bound method, and then discard the bound-method-object, there is no
point in creating it first. The exception is the getattr-style
computation of callables, where getattr cannot know that the result is
going to be called right away.

Regards,
Martin



More information about the Python-Dev mailing list