Bulletmagnet
Bulletmagnet

Reputation: 6010

Modifying the default value of a function argument

I have the following modules:

cat.py:

DEFAULT_SOUND='meow'

def make_sound(sound=DEFAULT_SOUND):
    print(sound)

animal.py

import cat

def sound():
    cat.make_sound()

I need to call animal.sound, but I'd like the cat to make a different sound. I tried this:

import animal

# Change the sound
import cat
cat.DEFAULT_SOUND='nyan'

animal.sound()

but it didn't work (the output is meow). In retrospect, this is not surprising if the default value was set from the value of DEFAULT_SOUND at the time cat.py was processed by Python.

Is there a way for the cat to make a different sound? Neither animal.py nor cat.py is editable by me, although I can ask their maintainers to make changes. animal.sound is actually several nested calls, and it's impossible to change all of them to pass a sound through.

Upvotes: 1

Views: 66

Answers (1)

ywbaek
ywbaek

Reputation: 3031

You can use partial function from functools module.
Here is the documentation.

Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords.

from functools import partial

import animal
import cat

cat.make_sound = partial(cat.make_sound, sound='nyan')

animal.sound()
nyan

Upvotes: 3

Related Questions