Frustrated with scopes

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Wed Aug 12 14:20:26 CEST 2009


On Wed, 12 Aug 2009 04:49:06 -0700, andrew cooke wrote:

>> It would be helpful if you were to describe the type of behavior you
>> expect.
> 
> Sorry, I didn't make myself clear.  When run the code gives
>  NameError: name 'source' is not defined
> because the class namespace blocks the function namespace (or
> something...).

James asked you to describe the behaviour you expect. Please explain what 
you expect, and what you actually get. Post the ACTUAL error message, not 
a summary, not a paraphrase, but an actual copy and paste.


In any case, your code snippet works for me:


>>> class _StreamFactory(object):
...     @staticmethod
...     def __call__(lines, source, join=''.join):
...         class Line(object):
...             __source = source
...             __join = join
...
>>> obj = _StreamFactory()
>>> obj(['a', 'b'], "ab")
>>>

No errors. Of course it doesn't return anything, because your code 
snippet doesn't return anything either. Here's a modified version which 
returns the inner class:

>>> class _StreamFactory2(object):
...     @staticmethod
...     def __call__(lines, source, join=''.join):
...         class Line(object):
...             __source = source
...             __join = join
...         return Line
...
>>> obj = _StreamFactory2()
>>> K = obj(['a', 'b'], "ab")
>>> K
<class '__main__.Line'>
>>> K._Line__source
'ab'


Works perfectly. I suspect your error is probably something like you have 
misspelled "source" somewhere.


-- 
Steven



More information about the Python-list mailing list