Diez B. Roggisch wrote: > Kay Schluehr wrote: > > > > > Tomi Lindberg wrote: > >> Hi, > >> > >> With the following function definition, is it possible to > >> create an instance of class C outside the function f (and if > >> it is, how)? > > > > def f(): > > class C(object): > > def __init__(self): > > self.a = 'a' > > f.C = C > > return C() > > > >>>> f.C > > <class '__main__.C'> > > Not working, unless f has been called at least once.
Right. > But what I didn't know > (and always wondered) if the classdefinition inside a function can use the > outer scope - and apparently, it can! Cool. Yes, the bytecode simply refers to a global name f in the scope of __init__. Fortunately the Python compiler is too stupid to guess what f might be but simply expects that f exists at runtime. I use this "snake is eating itself" pattern very often for passing a module as a reference to another module inside of itself: --------------------- Module M import B def eatMe(): import M B.m = M if __name__ == '__main__': eatMe() ----------------------------------- One might consider M as a component which is definig stuff. Once you select such a component it can be used to configure a framework F of which B is a part ( B doesn't import M ! ) So F is essentially parametrized by M. You ere entering the next level when different parametrizations F(M1), F(M2),... can coexist or even refer to each other. This isn't just a mental exercise but it's going to be the way EasyExtend will support multiple extension languages at the same time in the fist beta version of the program. Yes, I know ... everything is heavily cyclic and we should do hierarchies instead ;) -- http://mail.python.org/mailman/listinfo/python-list