Dynamic class problem

Fredrik Lundh fredrik at pythonware.com
Wed Jun 6 02:22:03 CEST 2001


Robin Becker wrote:
> I'm trying to figure out how to recode a class that is giving a shadow
> warning under 2.1

I don't have the mental bandwidth to figure out what you're
doing here, but I can explain why you're getting that error:

> the relevant code is
>
>     def __getitem__(self, index):
>         try:
>             return self._children[index]
>         except KeyError:
>             Klass = self._prototype

here, you create a local variable named "Klass".

>             if Klass in _ItemWrapper.keys():

(you meant _ItemWrapper.has_key(Klass), didn't you?)

>                 WKlass = _ItemWrapper[Klass]
>             else:
>                 class WKlass(Klass):

here, you refer to that local variable.

>                     def __getattr__(self,name):
>                         try:
>                             return Klass.__getattr__(self,name)

here, you access a *global* variable named Klass.  under 2.2,
this will refer to the local variable instead.

>                         except:
>                             return getattr(self._parent,name)
>                 _ItemWrapper[Klass] = WKlass
>
>             child = WKlass()
>             child._parent = self
>             for i in filter(lambda x,K=child.__dict__.keys(): x in K,child._attrMap.keys()):
>                 del child.__dict__[i]
>
>             self._children[index] = child
>             return child
>
> the idea is that I want to generate a child instance based on the _prototype class
> which has a single overridden getattr method. This code seemed to be working in 2.0,
> but I'm getting warnings now

do you have a global Klass class?  if not, 2.1 just pointed out that
your code didn't always work...

Cheers /F





More information about the Python-list mailing list