Help with dynamic attributes.

Fredrik Lundh fredrik at
Mon Jan 9 09:50:24 EST 2006

"Mr.Rech" wrote:

> class foo(object):
>    def __init__(self, list_of_lists):
> = list(list_of_lists)
>        for i in range(len(list_of_lists)):
>            exec 'self.x%d =[%d]' % (i, i)
>        self.shape = tuple(len(item) for item in

generator expressions are anonymous functions, and the "self" in that line
is a free variable (that is, it belongs to an outer scope).  Python uses static
analysis to identify free variables, and that doesn't mix well with exec.

> Any better way to get the same attributes I got with the exec statement?

use setattr(self, name, value)


More information about the Python-list mailing list