51
def save_file(self, outputfilename = self.image_filename): 
    self.file.read(outputfilename)
    ....

gives NameError: name 'self' is not defined in the first line. It seems that Python doesn't accept it. How can I rewrite the code so it doesn't raise an exception?

wpercy
  • 9,636
  • 4
  • 33
  • 45
Framester
  • 33,341
  • 51
  • 130
  • 192
  • The function definition takes place in a different scope and at a different time. – Felix Kling Sep 10 '11 at 11:22
  • Sure would be nice if it did work. Makes the code a lot cleaner. I'm guessing it would open some other Pandoran Box to implement? – JS. Aug 26 '13 at 22:00

4 Answers4

50

Use a default of None and detect that.

def save_file(self, outputfilename=None): 
    if outputfilename is None:
        outputfilename = self.image_filename
    self.file.read(outputfilename)
    ....
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
14

The documentation states:

Default parameter values are evaluated when the function definition is executed.

This explains why the instance cannot be referenced. As others have said, use None as your default and fix up the value at function execution time when the instance is available.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
10
def save_file(self, outputfilename=None): 
    outputfilename = outputfilename or self.image_filename
    self.file.read(outputfilename)

or even

def save_file(self, outputfilename=None):         
    self.file.read(outputfilename or self.image_filename)

This may be nothing with one variable, but if you have, let's say, 5, this makes code easier to read, in my opinion.

petr0
  • 411
  • 7
  • 10
3
def save_file(self, outputfilename = None):
    if not outputfilename:
        outputfilename = self.image_filename 
    self.file.read(outputfilename)
    ....
Alexander Poluektov
  • 7,844
  • 1
  • 28
  • 32