Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using self.* as default value for a method [duplicate]

Tags:

python

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?

like image 999
Framester Avatar asked Sep 10 '11 10:09

Framester


3 Answers

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)
    ....
like image 101
Ignacio Vazquez-Abrams Avatar answered Nov 16 '22 22:11

Ignacio Vazquez-Abrams


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.

like image 20
David Heffernan Avatar answered Nov 17 '22 00:11

David Heffernan


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.

like image 9
petr0 Avatar answered Nov 16 '22 23:11

petr0