views:

88

answers:

2
class Test:

    def somemethod(self):
        def write():
            print 'hello'

        write()

x = Test()
x.somemethod()

write() is a function that will be used several times through somemethod(). somemethod() is the only function within the class that will require it's use so it seems silly to define it outside of somemethod(). Closure seems like the way to go.

When I run that code, I get the following error:

TypeError: somemethod() takes exactly 2 arguments (1 given)

What am I doing wrong? Is self getting passed to write()? :/

+3  A: 

I find it impossible to reproduce the problem you report:

>>> class Test(object):
...   def somemethod(self):
...     def write():
...       print 'hello'
...     write()
... 
>>> x = Test()
>>> x.somemethod()
hello
>>> 

so I believe you must have done some transcription error, or something. What do you see when you run exactly the code I'm showing here? (Works identically in Python 2.4, 2.5, 2.6, 2.7, on all platforms).

Alex Martelli
It seems my bug lied elsewhere... Thanks for clearing my head
brad
A: 

It also works for me:

>>> class Test:
...     def somemethod(self):
...         def write():
...             print 'hello'
...         write()
... 
>>> 
>>> x = Test()
>>> x.somemethod()
hello
>>>     

I think you might be using tabs and spaces, or your identation is wrong

Rafael SDM Sierra