Order in metaclass

Bengt Richter bokr at oz.net
Wed Oct 13 17:55:09 EDT 2004


On Wed, 13 Oct 2004 15:07:32 -0300, Carlos Ribeiro <carribeiro at gmail.com> wrote:

>On Wed, 13 Oct 2004 18:18:02 +0200, Peter Otten <__peter__ at web.de> wrote:
>> Carlos Ribeiro wrote:
>> 
>> > executed (which count() can guarantee). There are two situations where
>> > the simpler counter works, but the getframe hack doesn't:
>> >
>> > -- if I have a loop inside my class that is used to declare bunch of
>> > attributes, all of them will have the same line number... but a
>> > different sequence number if the simpler method is chosen.
>> >
>> > -- if a function is called that returns a bunch of attributes (not
>> > common practice, but still possible). All attributes are at the same
>> > line in this case. Example:
>> >
>> > class Foo:
>> > a,b,c = myfunc(...)
>> 
>> Do you have an example handy? I had so far no success breaking Bengt's code.
>
>Ok. Just as an exercise -- at this point we're far from safe Python
>land anyway, and it's not recommended to push it beyond this limit...
>;-) Pseudo code only:
>
>class Foo:
>    # loop that creates attributes out of a list
>    for name, val in list:
>        locals()[name] = val
>
Sure, the compiler has to see the names in order for them to get into co_names in the frame.

>or (actual code tested):
>
>>>> class Bar:
>... 	a,b,c,d = (1,2,3,4)
>... 	
>>>> vars(Bar)
>{'a': 1, '__module__': '__main__', 'b': 2, 'd': 4, 'c': 3, '__doc__': None}
>
>The ordering became (a,b,d,c); and the code would have no way to tell
>that 'c' was supposed to be classified before 'd', because the
>getframe trick would return the same line.
>
The "getframe trick" (if you mean my hack ;-) is not using line numbers,
so I don't know what you mean:

 >>> class C(object):
 ...     __metaclass__ = MC # really a function shortcut
 ...     a,b,c,d = (1,2,3,4)
 ...     ordic = getnames()
 ...
 >>> C.ordic
 {'a': 2, 'ordic': 6, '__module__': 0, 'b': 3, '__metaclass__': 1, 'd': 5, 'c': 4}

Regards,
Bengt Richter



More information about the Python-list mailing list