Frustrated with scopes

James Stroud nospamjstroudmapson at
Wed Aug 12 07:51:12 CEST 2009

andrew cooke wrote:
> Is there a way to make this work (currently scope and join are
> undefined at runtime when the inner class attributes are defined):
> class _StreamFactory(object):
>     @staticmethod
>     def __call__(lines, source, join=''.join):
>         class Line(object):
>             __source = source
>             __join = join
> [...]

It would be helpful if you were to describe the type of behavior you expect.

I assume you will return the newly created Line class when you call an 
instance of _StreamFactory? There may be some things about the above 
that you might be overlooking:

1. __call__ does not supersede the __init__ constructor of _StreamFactory.
2. __source and __join are name-mangled in later versions of python. 
They will be attributes of the returned Line class named _Line_source 
and _Line_join respectively.

Rather than make _StreamFactory a class, you will probably get the 
behavior you desire if you simply make it a function:

def stream_factory:
   class Line(object):
     __source = source
     __join = join
   # etc.
   return Line

And then don't forget that double underscores produce name mangling and 
you'll be set.


More information about the Python-list mailing list