Set run vars with each call

Steven D'Aprano steve+comp.lang.python at
Tue Jul 12 20:44:54 EDT 2011

Gnarlodious wrote:

> Question. Is there a special method or easy way to set default values
> with each call to an instance? Any ideas to make it easier? What I
> want to do is have a constantly updating set of values which can be
> overridden. Just thought there was an easy way to set that up.

All the words are in English, but the sentences make no sense :)

Seriously, I don't understand what you mean. "Call to an instance"? Do mean
treating instances as a callable (like a function), or do you mean calling
an arbitrary method?

To make an instance itself callable, define a __call__ method.

What do you mean, "constantly updating set of values that can be
overridden"? Perhaps a simple example might help.

The closest thing I can think of, might be: you want to store a data
attribute in an instance, and use that if the caller doesn't specify
differently. Something like:

class Parrot:
    name = "Polly"
    def speak(self, name=None):
        if name is None:
            name =
        print("%s wants a cracker!" % name)

And in use:

>>> p = Parrot()
>>> p.speak()
Polly wants a cracker!
>>> p.speak("Peter")
Peter wants a cracker!
>>> = "Penelope"
>>> p.speak()
Penelope wants a cracker!

If None is a legitimate value, then you can define your own sentinel to use

MISSING = object()  # Unique object guaranteed not to be used by the caller.
# (Guarantee void on planet Earth.)

then replace None by MISSING in the code above.

Is this the sort of scenario you are talking about? If not, I'm completely


More information about the Python-list mailing list