When do default parameters get their values set?

Chris Angelico chris.angelico at 1
Tue Dec 9 11:32:01 EST 2014


  To: bSneddon
Copy: python-list at python.org (python-list at python.org)

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

--- SoupGate-Win32 v1.05
 * Origin: <SpaceSST.BBS.Fidonet<>NNTP.gateway. at .piz.noip.me> (1:249/999)
--- Synchronet 3.15b-Win32 NewsLink 1.92
SpaceSST BBS Usenet <> Fidonet Gateway



More information about the Python-list mailing list