Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #82152
| References | <8c10ecec-c057-4580-9711-94c0a5151646@googlegroups.com> |
|---|---|
| From | Chris Kaynor <ckaynor@zindagigames.com> |
| Date | 2014-12-08 14:28 -0800 |
| Subject | Re: When do default parameters get their values set? |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.16739.1418077725.18130.python-list@python.org> (permalink) |
[Multipart message — attachments visible in raw view] - view raw
On Mon, Dec 8, 2014 at 2:10 PM, bSneddon <w.g.sneddon@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
Here is your problem. The default argument value is evaulated at the time
the function is defined, not when it is called, so argT will boung to
'blue' by default, unless overridden in the call.
In this simple case, you could just change the function to:
def printDef():
print cfg['def']
In more complicated cases, where you actually need to pass in the argument
with a default, the best way is to use a sentinel value (I'm using None in
the case):
def printDef(argT = None):
argT = argT or cfg['def'] # If argT could be False or another "falsy"
value, use "argT = argT if argT is not None else cfg['def']". This is also
useful if None needs to be a valid value.
print argT
>
>
> #module name feTest
> import beTest
>
> beTest.cfg['def'] = "no red"
> beTest.printDef()
>
>
>
> This prints blue. I suppose because I am changing a local copy of cfg
> dictionary. What is the write approach here?
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
When do default parameters get their values set? bSneddon <w.g.sneddon@gmail.com> - 2014-12-08 14:10 -0800 Re: When do default parameters get their values set? Chris Angelico <rosuav@gmail.com> - 2014-12-09 09:28 +1100 Re: When do default parameters get their values set? Chris Kaynor <ckaynor@zindagigames.com> - 2014-12-08 14:28 -0800 Re: When do default parameters get their values set? Dave Angel <davea@davea.name> - 2014-12-08 17:30 -0500 Re: When do default parameters get their values set? Tim Chase <python.list@tim.thechases.com> - 2014-12-08 16:26 -0600 Re: When do default parameters get their values set? bSneddon <w.g.sneddon@gmail.com> - 2014-12-08 15:35 -0800 Re: When do default parameters get their values set? Terry Reedy <tjreedy@udel.edu> - 2014-12-08 20:37 -0500
csiph-web