When do default parameters get their values set?

Chris Angelico rosuav at gmail.com
Mon Dec 8 17:28:02 EST 2014


On Tue, Dec 9, 2014 at 9:10 AM, bSneddon <w.g.sneddon at gmail.com> wrote:
> I ran into an issue setting variables from a GUI module that imports a back end module.  My approach was wrong obviously but what is the best way to set values in a back end module.
>
> #module name beTest.py
>
> cfg = { 'def' : 'blue'}
>
> def printDef(argT = cfg['def']):
>         print argT

They're set when you define the function, and become attributes of the function.

If you want to lazily fetch the defaults, here's one common idiom:

def printDef(argT=None):
    """Print the argT value, defaults to cfg['def']"""
    if argT is None: argT = cfg['def']
    print(argT)

This depends on None not being a meaningful argument value, of course.
If you need to have any object at all able to be passed in, you'd need
to create a dedicated sentinel object, or use *args and unpack
yourself; but for a lot of cases, None works fine.

ChrisA



More information about the Python-list mailing list