0

This is a piece of my code...

def contactMaster(data="",url= str(chosenMaster)+"todolist"):
    print "url: "+url

It prints only "todolist" instead of "http://www.mysite.com/blah/1234/todolist"

Why isn't it working??

agf
  • 171,228
  • 44
  • 289
  • 238
spatara
  • 893
  • 4
  • 15
  • 28
  • How are you calling it, and what is chosenMaster? If chosenMaster is empty then is should print `url: todolist`. Please show a complete example. – aquavitae Apr 11 '12 at 18:16

3 Answers3

6

Default arguments are evaluated when the function is defined not when it is executed. So if chosenMaster is empty when Python defines contactMaster, it will print only todolist.

You need to move str(chosenMaster) into the function.

See Default Argument Values in the Python Tutorial for more info. The example there is:

The default values are evaluated at the point of function definition in the defining scope, so that

i = 5

def f(arg=i):
    print arg

i = 6
f()

will print 5.

DSM
  • 342,061
  • 65
  • 592
  • 494
agf
  • 171,228
  • 44
  • 289
  • 238
  • Is it possible to declare, but not initialize global variable in python? In the example, in order get it to print 6, would I have to make i=6, then print i? – spatara Apr 11 '12 at 18:28
  • @spatara No. In order to get it to print `6`, you'd either have to have it be `6` _before_ the function _definition_ (where it's `5`) or move the evaluation of `i` into the body of the function, which will get executed _after_ `i` has been set to `6`. – agf Apr 11 '12 at 18:39
  • Yep! got it, my program works...I gave it the value I wanted when I declared it :) – spatara Apr 11 '12 at 19:11
1

The function definition captures the value of chosenMaster at the time the function is declared, not when the function is called.

Do this instead:

def contactMaster(data='', url=None):
    if url is None:
        url = str(chosenMaster) + 'todolist'
    print 'url: ' + url
Tim Lesher
  • 6,341
  • 2
  • 28
  • 42
0

Because default function arguments are determined when the function is defined. Changing chosenMaster after the fact will have no effect.

Community
  • 1
  • 1
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358