0

If I have the object

>>> class example_class():
>>>    def example_function(number, text = 'I print this: '):
>>>        print text, number

I can change the example_function input parameter

>>> example_instance = example_class()
>>> print example_instace.example_function(3, text = 'I print that: ')

Now I would like to always use I print that: every time I use example_instace. Is it possible to change the default value of text so that I get this behavior:

>>> example_instace = example_class()
>>> print example_instance.example_function(3)
I print this: 3
>>> default_value(example_instance.text, 'I print that: ')
>>> print example_instance.example_function(3)
I print that: 3
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Niek de Klein
  • 8,524
  • 20
  • 72
  • 143

1 Answers1

2

Function defaults are stored with the function, and the function object is used to create the method wrapper. You cannot alter that default on a per-instance basis.

Instead, use a sentinel to detect that the default has been picked; None is a common sentinel suitable for when None itself isn't a valid value:

class example_class():
    _example_text_default = 'I print this: '
    def example_function(self, number, text=None):
        if text is None:
            text = self._example_text_default
        print text, number

and then simply set self._example_text_default on a per-instance basis to override.

If None is not a suitable sentinel, create a unique singleton object for the job:

_sentinel = object()

class example_class():
    _example_text_default = 'I print this: '
    def example_function(self, number, text=_sentinel):
        if text is _sentinel:
            text = self._example_text_default
        print text, number

and now you can use example_class().example_function(42, None) as a valid non-default value.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343