[Python-3000] Change to class construction?

Nick Coghlan ncoghlan at gmail.com
Mon Jul 9 13:03:15 CEST 2007


Brian Harring wrote:
> 
> I'd be curious if there is anyway to preserve the existing behaviour; 
> 
> class foo:
>   some_list = ('blacklist1', 'blacklist2')
>   known_bad = some_list += ('blah',)
>   locals().update([(attr, some_callable) for attr in some_list])
> 
> is slightly contrived, but I use similar code quite often for method 
> generation- both for tests, and standard enough objects.  Realize I 
> could do the same via metaclasses, but it's an extra step and not 
> nearly as easy/friendly imo.
> 
> So... anyway to preserve that trick under py3k?

As you've written it, that trick isn't affected by the semantic change 
at all (as the expression inside the list comprehension doesn't try to 
refer to a class variable).

If 'some_callable' was actually a method of the class, then you'd need 
to use an actual for loop instead of the list comprehension:

class foo(object):
    some_list = ('blacklist1', 'blacklist2')
    def some_method(self):
      # whatever
      pass
    for attr in some_list:
      locals()[attr] = some_method

However, I will point out that setting class attributes via locals() is 
formally undefined (it happens to work in current versions of CPython, 
but there's no guarantee that will always be the case).

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-3000 mailing list