f



When do default parameters get their values set?

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
 

#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?


Thanks

Bill
0
bSneddon
12/8/2014 10:10:43 PM
comp.lang.python 77058 articles. 6 followers. Post Follow

6 Replies
406 Views

Similar Articles

[PageSpeed] 1

On 2014-12-08 14:10, bSneddon 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']):

At this point (after the "def" has completed defining the function),
the expression is evaluated and assigned to the default argument.

> 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?

Well, you can bind to a default dictionary rather than an entry in
that dictionary:


  cfg = {'def': 'blue'}
  def printDef(config=cfg):
    ...
    access(config['def'])

which will make the look-up happen at run-time rather than
definition/bind-time.

  beTest.cfg['def'] = 'Red!'
  beTest.printDef()
  # should print "Red!"

-tkc



0
Tim
12/8/2014 10:26:31 PM
On Tue, Dec 9, 2014 at 9:10 AM, 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

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
0
Chris
12/8/2014 10:28:02 PM
--089e01227b0eaec9e70509bbf2fa
Content-Type: text/plain; charset=UTF-8

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?

--089e01227b0eaec9e70509bbf2fa
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable

<div dir=3D"ltr"><div class=3D"gmail_extra"><div class=3D"gmail_quote">On M=
on, Dec 8, 2014 at 2:10 PM, bSneddon <span dir=3D"ltr">&lt;<a href=3D"mailt=
o:w.g.sneddon@gmail.com" target=3D"_blank">w.g.sneddon@gmail.com</a>&gt;</s=
pan> wrote:<br><blockquote class=3D"gmail_quote" style=3D"margin:0px 0px 0p=
x 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-lef=
t-style:solid;padding-left:1ex">I ran into an issue setting variables from =
a GUI module that imports a back end module.=C2=A0 My approach was wrong ob=
viously but what is the best way to set values in a back end module.<br>
<br>
#module name beTest.py<br>
<br>
cfg =3D { &#39;def&#39; : &#39;blue&#39;}<br>
<br>
def printDef(argT =3D cfg[&#39;def&#39;]):</blockquote><blockquote class=3D=
"gmail_quote" style=3D"margin:0px 0px 0px 0.8ex;border-left-width:1px;borde=
r-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
=C2=A0 =C2=A0 =C2=A0 =C2=A0 print argT</blockquote><div><br></div><div>Here=
 is your problem. The default argument value is evaulated at the time the f=
unction is defined, not when it is called, so argT will boung to &#39;blue&=
#39; by default, unless overridden in the call.</div><div>In this simple ca=
se, you could just change the function to:</div><div><br></div><div>def pri=
ntDef():</div><div>=C2=A0 =C2=A0 print cfg[&#39;def&#39;]</div><div><br></d=
iv><div>In more complicated cases, where you actually need to pass in the a=
rgument with a default, the best way is to use a sentinel value (I&#39;m us=
ing None in the case):</div><div><br></div><div>def printDef(argT =3D None)=
:</div><div>=C2=A0 =C2=A0 argT =3D argT or cfg[&#39;def&#39;] # If argT cou=
ld be False or another &quot;falsy&quot; value, use &quot;argT =3D argT if =
argT is not None else cfg[&#39;def&#39;]&quot;. This is also useful if None=
 needs to be a valid value.</div><div>=C2=A0 =C2=A0 print argT</div><div>=
=C2=A0</div><blockquote class=3D"gmail_quote" style=3D"margin:0px 0px 0px 0=
..8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-s=
tyle:solid;padding-left:1ex">
<br>
<br>
#module name feTest<br>
import beTest<br>
<br>
beTest.cfg[&#39;def&#39;] =3D &quot;no red&quot;<br>
beTest.printDef()<br>
<br>
<br>
<br>
This prints blue.=C2=A0 =C2=A0 =C2=A0 I suppose because I am changing a loc=
al copy of cfg dictionary.=C2=A0 What is the write approach here?</blockquo=
te></div></div></div>

--089e01227b0eaec9e70509bbf2fa--
0
Chris
12/8/2014 10:28:18 PM
On 12/08/2014 05:10 PM, bSneddon 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.
>

To answer the subject line, the default parameter(s) are evaluated when 
the function is compiled, and then stored with the function.  So in this 
case the default for argT is an immutable string "blue"  Being 
immutable, nothing will change that for the run of the program.

> #module name beTest.py
>
> cfg = { 'def' : 'blue'}
>
> def printDef(argT = cfg['def']):
> 	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?
>

You're not making a local copy of any dictionary.  The symptoms you have 
would be identical even if you run beTest.py directly (with those two 
lines added, of course).

The RIGHT approach depends on what your goal is here.  Obviously this is 
simplified from some more complex use, but you haven't stated what your 
desires are, so I don't necessarily know how to achieve them.

There is only one dictionary, and it does change when you you say:
    beTest.cfg['def'] = "no red"

But if you need to do a lookup in that dictionary upon calling 
primtDef(), then you're going to make the evaluation at that time, not 
at default-time.

How about the following, fairly common idiom for default values:

def printDef(argT = None]):
     if argT = None:
         argT = cfg['def']
     print argT





-- 
DaveA

0
Dave
12/8/2014 10:30:57 PM
Thanks to all.  I now understand what is happening.   Originally wrote a script  be executed from command line.   No want to use Gui to change defaults.   Will refactor to fix where necessary.

On Monday, December 8, 2014 5:10:58 PM UTC-5, bSneddon 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
>  
> 
> #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?
> 
> 
> Thanks
> 
> Bill
0
bSneddon
12/8/2014 11:35:19 PM
 >>> def f(a="default "+"arg value"): return a

 >>> f.__defaults__
('default arg value',)

Before any calls, the expression has be evaluated.  When f() is called 
with no arg, the local name 'a' is associated with
'default arg value'. Then code execution begins. Use dir(f), for 
instance, to invesigate internals.

-- 
Terry Jan Reedy

0
Terry
12/9/2014 1:37:58 AM
Reply:

Similar Artilces:

When do default parameters get their values set? #2
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 #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? Thanks Bill --- SoupGate-Win32 v1.05 ...

How to set LANG varible for a default value
Hello All, I would like to set my LANG environmental variable to en_US by default. Currently it is set to "no_NY". I tried to run /usr/sbin/locale_config to change it but in the list I did not find "en_US" locale. BTW, I have a Red Hat Linux 8 machine Can somebody suggest me how can I do this? Thanks -Vittal Vittal <vsnadagouda@yahoo.com> wrote: > I would like to set my LANG environmental variable to en_US by > default. Currently it is set to "no_NY". I tried to run > /usr/sbin/locale_config to change it but in the list I did no...

setting default value for template parameter list
I want to accomplish the following void foo(const T &v1, const T &v2) { if(v1&v2 is of type double) double alpha=1.0; else if (v1&v2 is of type complex double) complex double alpha=(1.0,1.0); bar(v1,v2,alpha); } void bar(const T&v1, const T&v2, const T& alpha) { } but dont know how. Please help Regards, bluekite2000@gmail.com wrote: > I want to accomplish the following > > void foo(const T &v1, const T &v2) > { > if(v1&v2 is of type double) ?? Is foo supposed to be a template? > double alpha=1.0; > else if (v1&...

is it possible to get hidden parameter values using window.opener.document.form.parameter.value.
is it possible to get hidden parameter values using window.opener.document.form.parameter.value. I am getting this error " Object not found" Please help Abdul Abdul Mohsin said: > >is it possible to get hidden parameter values using >window.opener.document.form.parameter.value. Yes. ...

A97 table field of Yes/No type without a default value property setting has a default value?
I have an A97 table with a Yes/No field named TowJob and a form bound to that table. The TowJob control on the form is bound to the same field. It is an option group with Yes and No bttns valued at -1 and 0 respectively. Unless I specifically set the table field's defaultvalue to Null, the form comes up with an automatic value of 0 in the control? The control has NO default value property setting. Why is that? Why must one EXPLICITYLY set a table field's defaultvalue property to Null instead of simply entering nothing at all into the defaultvalue property setting field? MLH wrote: ...

idea on how to get/set nested python dictionary values
hello! i am trying to come up with a simple way to access my values in my nested python dictionaries here is what i have so far, but i wanted to run it by the geniuses out there who might see any probems with this... here is an example: +++++++++++++++++++++++++++++++++++++++ def SetNewDataParam(Data, paramPath, NewData): ParamList = paramPath.split('/') numParams = len(ParamList) for i in range(0, numParams): if i != (numParams-1): Data = Data[ParamList[i]] else: Data[ParamList[i]] = NewData Data = {'a':{'...

To get layout default mos parameters value for pcell ??
Is there any command to get the pcell parameter value in layout. Actually I have a code to do it.. but for default values its showing as nill. If we change the value of user defined parameters it print the value. How to get those default values?? --- vijayraj On 02/15/14 14:36, vijayraj wrote: > Is there any command to get the pcell parameter value in layout. > Actually I have a code to do it.. but for default values its showing > as nill. If we change the value of user defined parameters it print > the value. How to get those default values?? > --- > vijayraj > ...

setting default value for a parameter of a class member function
I have class Foo { .... .... //copy constructor Foo(const Foo<T>& F, int size=F.size()) { ... ... } and get this error error: `F' was not declared in this scope Any solution to this? bluekite2000@gmail.com wrote: > I have > class Foo > { > ... > ... > //copy constructor > Foo(const Foo<T>& F, int size=F.size()) > { > .. > .. > } > > and get this error > error: `F' was not declared in this scope > > Any solution to this? Foo(const Foo<T>& F) { int size = F.size(); ..... } or, if you really need...

How to get default values to parameters of class object member methods [incr tcl]
Hello again, Thanks to all for helping fix my simple blunder. Now I've got another one and I'm not sure if there is a resolution. I've tried a few different things, but nothing seems to be working. As well all know, if a proc is to have a default value for a parameter, it's defined something like this: proc someproc { { param = foo } } { # doing lots of important stuff } Well, I've tried something similar in my classes but the interpreter is always complaining about "too many fields in argument specifier " i = 234 "". This was with something l...

set text box default value to be the current value
I've got a text box on a form where the default value shows - C:/ The user can change the default to whatever they want - D:/ I'd like to put a button next to the field that will change the default from C:/ to D:/ so the next time the form is opened D:/ is showing. Any ideas? Thanks Charlie Hi Charlie Put all your default settings in a table and populate controls with these on loading the form. Your defaults table only needs to be a couple of fields - one for the name of the default and say a text field to carry the default setting. Text field is good cause you can put anythin...

Setting value of Python variable in a Python C extension
Hi, I have a function developed in C that is being used as a Python extension. The function is being passed a variable from the Python program. Is it possible to change the value of this variable from within the C function? Thanks, -MD On Mon, 2007-10-01 at 09:08 -0700, MD wrote: > Hi, > I have a function developed in C that is being used as a Python > extension. The function is being passed a variable from the Python > program. Is it possible to change the value of this variable from > within the C function? That question is ill-defined because Python doesn't have...

Must GET/POST Parameters Have Values? (And What is the Syntax for GET, If NOT)
Are GET and POST parameters required to have values, i.e. are either of these legal? http://www.mydomain.com/index.php?this&that http://www.mydomain.com/index.php?this=&that= In my application, I have a GET/POST parameter that is significant just by its presence (it doesn't need a value), and rather than say this=1&that=1 I was wondering if it is legal to specify them without values. Thanks, Dave. David T. Ashley wrote: > Are GET and POST parameters required to have values, i.e. are either of > these legal? > > http://www.mydomain.com/index.php?this&am...

HP aCC auto_ptr as value parameter with default value problem
I'm pulling my hair out here. I have some code that works on a number of platforms and compilers (gcc 2.96 and 3.x and also Sun Workshop C++). It makes extensive use of auto_ptr value parameters to make explicit that ownership of objects is being passed into functions. So, littered around the code are functions of the form: void foo(std::auto_ptr<T> t){...} With the callers calling them as: // do some stuff // create T and pass it into foo foo(std::auto_ptr<T>(new T)); However, some of the time I want to be able to default initialise the values passed into t...

stl map with bool values: set default value to false
Let's say we have a stl map with bool values. Is it possible to set it such that, if we pass to operator[] a key which doesn't have a value, the operator will return false instead of true? If so, can anyone please explain me how that can be done? Thanks in advance, Rui Maciel Rui Maciel wrote: > Let's say we have a stl map with bool values. Is it possible to set it such that, > if we pass to operator[] a key which doesn't have a value, the operator will return > false instead of true? If so, can anyone please explain me how that can be done? It is t...

Web resources about - When do default parameters get their values set? - comp.lang.python

Parameter - Wikipedia, the free encyclopedia
A parameter (from the Ancient Greek παρά , "para", meaning "beside, subsidiary" and μέτρον , "metron", meaning "measure"), in its common meaning, ...

fb_source Parameter - Facebook-Entwickler
This document lists the complete list of values for the fb_source parameter that is returned with th...

Google / Firefox Parameter - Flickr - Photo Sharing!
HS what? www.seroundtable.com/archives/017105.html

Cat 8: TIA performance standards committee chairman previews parameters of forthcoming twisted-pair cable ...
Category 8, the next-generation twisted-pair cabling specification, is still in development, but the outlook looks quite positive that it will ...

Philippine president asks for 'parameters' of Mayon Volcano tours
Philippine president asks for 'parameters' of Mayon Volcano tours People's Daily Online ... 26, 27, 28, 29, 30, 31. Jan, Feb, Mar, Apr, May, ...

Alternatives to boolean parameters
... ) { PrintLine ( item . Name ); if ( printDetails ) { PrintLine ( item . Description ); } } } Aha! Now can see that the boolean parameter ...

Exporting Error (Error in Parameter...: Apple Support Communities
This site contains user submitted content, comments and opinions and is for informational purposes only. Apple disclaims any and all liability ...

Apple tech monitors device aging, adjusts operating parameters to ensure optimal performance
... describing a method of monitoring the aging of a device's electronics, comparing the data with a global average and modifying operating parameters ...

Is it poor programming practice to pass parameters as objects?
... a free, community-powered network of 100+ Q&A sites . Risser asked: So, we've got a guy who likes to write methods that take Objects as parameters, ...

Parameter Short Film Competition sponsored by Grolsch
Grolsch presents Parameter The A.V. Club Short Film Competition Please Enter Your Date of Birth Ineligible entry Enter For people over the age ...

Resources last updated: 1/26/2016 6:00:20 AM