Default Values for function parameters in Python

paweloque picture paweloque · Nov 2, 2012 · Viewed 110.1k times · Source

Possible Duplicate:
default value of parameter as result of instance method

While it is possible to set default values to function parameters in python:

def my_function(param_one='default')
    ...

It seems not to be possible to access the current instance (self):

class MyClass(..):

    def my_function(self, param_one=self.one_of_the_vars):
        ...

My question(s):

  • Is this true that I cannot access the current instance to set the default parameter in functions?
  • If it is not possble: what are the reasons and is it imaginable that this will be possible in future versions of python?

Answer

Jon Clements picture Jon Clements · Nov 2, 2012

It's written as:

def my_function(self, param_one=None): # Or custom sentinel if None is vaild
    if param_one is None:
        param_one = self.one_of_the_vars

And I think it's safe to say that will never happen in Python due to the nature that self doesn't really exist until the function starts... (you can't reference it, in its own definition - like everything else)

For example: you can't do d = {'x': 3, 'y': d['x'] * 5}