473,549 Members | 2,651 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

initialization in argument definitions

Hi, I know this is a terribly simple question, but the docs seem to be
designed for people who probably find a the answer to this question
terribly obvious. But its not at all obvious to me.

I can't figure out why when I define a function, a variable
(specifically a list) that I define and initialize in the argument
definitions, will not initialize itself every time its called. So for
example, when making a simple list of a counting sequence from num (a
range list), if I call the function multiple times, it appends the
elements to the list generated the times it was called before, even
though the variable for the list is initialized in the argument
definitions.

def foo_range(num,a List = []):
aList = []
#why is this seemingly extra initialization necessary? shouldn't it be
initialized in the argument definitions?
#but if its not there and the function is called multiple times the
elements generated (see below)
#append to the list generated before.
while num <= 10:
aList.append(nu m)
num +=1
else:
return aList

Why is this? Thanks, hope its not a stupid quesiton.
Nov 21 '08 #1
7 2071
On Fri, Nov 21, 2008 at 1:25 PM, Brentt <Br**********@g mail.comwrote:
Hi, I know this is a terribly simple question, but the docs seem to be
designed for people who probably find a the answer to this question
terribly obvious. But its not at all obvious to me.

I can't figure out why when I define a function, a variable
(specifically a list) that I define and initialize in the argument
definitions, will not initialize itself every time its called. So for
example, when making a simple list of a counting sequence from num (a
range list), if I call the function multiple times, it appends the
elements to the list generated the times it was called before, even
though the variable for the list is initialized in the argument
definitions.

def foo_range(num,a List = []):
That should probably be: def foo_range(num, aList=None):
aList = []
#why is this seemingly extra initialization necessary? shouldn't it be
initialized in the argument definitions?
#but if its not there and the function is called multiple times the
elements generated (see below)
#append to the list generated before.
while num <= 10:
aList.append(nu m)
num +=1
else:
return aList

Why is this? Thanks, hope its not a stupid quesiton.
No, but it is a very frequently asked one:
http://effbot.org/zone/default-values.htm

Cheers,
Chris
--
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list
Nov 21 '08 #2
On Nov 21, 4:25*pm, Brentt <BrenttNew...@g mail.comwrote:
Hi, I know this is a terribly simple question, but the docs seem to be
designed for people who probably find a the answer to this question
terribly obvious. But its not at all obvious to me.
Don't worry, it's not obvious to *anyone* new to Python (and many not-
so-new for that matter).
I can't figure out why when I define a function, a variable
(specifically a list) that I define and initialize in the argument
definitions, will not initialize itself every time its called. So for
example, when making a simple list of a counting sequence from num (a
range list), if I call the function multiple times, it appends the
elements to the list generated the times it was called before, even
though the variable for the list is initialized in the argument
definitions.

def foo_range(num,a List = []):
aList = []
#why is this seemingly extra initialization necessary? shouldn't it be
initialized in the argument definitions?
#but if its not there and the function is called multiple times the
elements generated (see below)
#append to the list generated before.
while num <= 10:
aList.append(nu m)
num +=1
else:
return aList

Why is this? Thanks, hope its not a stupid quesiton.
Sigh.. no it's not stupid at all; actually it is (and will probably
remain, unfortunately) the most FAQ of all times:
http://www.python.org/doc/faq/genera...etween-objects

George
Nov 21 '08 #3
On Nov 22, 8:25*am, Brentt <BrenttNew...@g mail.comwrote:
Hi, I know this is a terribly simple question, but the docs seem to be
designed for people who probably find a the answer to this question
terribly obvious. But its not at all obvious to me.

I can't figure out why when I define a function, a variable
(specifically a list) that I define and initialize in the argument
definitions, will not initialize itself every time its called.
Have you worked through the tutorial (which is part of the docs)? See
http://docs.python.org/tutorial/cont...rgument-values
.... look for "Important warning"

Nov 21 '08 #4
Brentt wrote:
Hi, I know this is a terribly simple question, but the docs seem to be
designed for people who probably find a the answer to this question
terribly obvious. But its not at all obvious to me.

I can't figure out why when I define a function, a variable
(specifically a list) that I define and initialize in the argument
definitions, will not initialize itself every time its called. So for
example, when making a simple list of a counting sequence from num (a
range list), if I call the function multiple times, it appends the
elements to the list generated the times it was called before, even
though the variable for the list is initialized in the argument
definitions.

def foo_range(num,a List = []):
aList = []
#why is this seemingly extra initialization necessary? shouldn't it be
initialized in the argument definitions?
#but if its not there and the function is called multiple times the
elements generated (see below)
#append to the list generated before.
while num <= 10:
aList.append(nu m)
num +=1
else:
return aList

Why is this? Thanks, hope its not a stupid quesiton.
The def statement is an executable statement that creates a function
object. When you execute the def statement, the parameter list,
including default arg object expressions, is evaluated for creating the
function object and its associated code object. The 'suite' that
follows the ':' and possible a doc string is compiled for the code object.

The language manual entry for Function definitions explains this, with
the first sentence in bold.
"Default parameter values are evaluated when the function definition is
executed. This means that the expression is evaluated once, when the
function is defined, and that that same “pre-computed” value is used for
each call. This is especially important to understand when a default
parameter is a mutable object, such as a list or a dictionary: if the
function modifies the object (e.g. by appending an item to a list), the
default value is in effect modified."

The allows a choice of having a 'default' evaluated either when the
function is defined, which is nearly always what is wanted, or when the
function is called, by using None or another flag object, and then testing.

tjr

Nov 21 '08 #5
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Brentt schrieb:
| Hi, I know this is a terribly simple question, but the docs seem to be
| designed for people who probably find a the answer to this question
| terribly obvious. But its not at all obvious to me.
|
| I can't figure out why when I define a function, a variable
| (specifically a list) that I define and initialize in the argument
| definitions, will not initialize itself every time its called. So for
| example, when making a simple list of a counting sequence from num (a
| range list), if I call the function multiple times, it appends the
| elements to the list generated the times it was called before, even
| though the variable for the list is initialized in the argument
| definitions.
|
| def foo_range(num,a List = []):
| aList = []
| #why is this seemingly extra initialization necessary? shouldn't it be
| initialized in the argument definitions?
| #but if its not there and the function is called multiple times the
| elements generated (see below)
| #append to the list generated before.
| while num <= 10:
| aList.append(nu m)
| num +=1
| else:
| return aList
|
| Why is this? Thanks, hope its not a stupid quesiton.

look up
http://docs.python.org/tutorial/cont...ning-functions

"The execution of a function introduces a new symbol table used for
the local variables of the function. More precisely, all variable
assignments in a function store the value in the local symbol table;
whereas variable references first look in the local symbol table, then
in the local symbol tables of enclosing functions, then in the global
symbol table, and finally in the table of built-in names. Thus, global
variables cannot be directly assigned a value within a function (unless
named in a global statement), although they may be referenced."

Egon

| --
| http://mail.python.org/mailman/listinfo/python-list

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFJJz2iZRi Do9Iq4qIRAhTLAJ 41TTysvN++TNF1t vanjAxBPhdBawCf e1tY
uDdbPYWBAEkbYNh bKQGkx88=
=9gL8
-----END PGP SIGNATURE-----
Nov 21 '08 #6
On Fri, 21 Nov 2008 13:25:45 -0800, Brentt wrote:
I can't figure out why when I define a function, a variable
(specifically a list) that I define and initialize in the argument
definitions, will not initialize itself every time its called.
Because you haven't told the function to initialize the value every time
it's called. You are laboring under a misapprehension . Function default
values are created ONCE, when you define the function.
So for
example, when making a simple list of a counting sequence from num (a
range list), if I call the function multiple times, it appends the
elements to the list generated the times it was called before, even
though the variable for the list is initialized in the argument
definitions.
No it isn't. You need to re-set your thinking, that's not what Python
does. Try this:

def expensive():
# simulate an expensive function call
import time
time.sleep(30)
return time.time()
def parrot(x=expens ive()):
return x

The expensive call is made once only. If you want it made every time, you
have to explicitly make that call every time:

def parrot(x=None):
if x is None:
x = expensive()
return x
For bonus marks, predict the behaviour of this:

def spam():
def ham(x=expensive ()):
return x
return ham()

--
Steven
Nov 22 '08 #7
George Sakkis wrote:
On Nov 21, 4:25 pm, Brentt <BrenttNew...@g mail.comwrote:
>Hi, I know this is a terribly simple question, but the docs seem to be
designed for people who probably find a the answer to this question
terribly obvious. But its not at all obvious to me.

Don't worry, it's not obvious to *anyone* new to Python (and many not-
so-new for that matter).
Speak for yourself, not for me.

Nov 22 '08 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
4609
by: Qin Chen | last post by:
I will present very long code, hope someone will read it all, and teach me something like tom_usenet. This question comes to me when i read <<Think in C++>> 2nd, chapter 10 , name control, section "Static initialization dependency". There is a example to show how to solve the prolem involved with a technique first poineered by Jerry Schwarz...
50
3748
by: Charles Stapleton | last post by:
Given the folowing class class Ctest{ public: Ctest( int i, int j) :a(i) { b = j; } private: int a, b; } When creating an object of type Ctest, what advantage is there to setting
4
9607
by: Aniruddha | last post by:
I want to initialize an array of function pointers (global) If I do it like: /* definition of foo_1, foo_2, foo_3 all return void and take no args */ void (* foo) (); foo = foo_1 ; foo = foo_2 ; foo = foo_3 ; I get a compile time error, but if initialized like :
5
2375
by: wkaras | last post by:
I've compiled this code: const int x0 = 10; const int x1 = 20; const int x2 = 30; int x = { x2, x0, x1 }; struct Y {
4
3695
by: Jess | last post by:
Hello, I tried several books to find out the details of object initialization. Unfortunately, I'm still confused by two specific concepts, namely default-initialization and value-initialization. I think default-init calls default constructor for class objects and sets garbage values to PODs. Value-init also calls default constructor for...
2
2369
by: timlyee | last post by:
int *p = new int; auto_ptr<intap1 = p; //will fail on 3 1 auto_ptr<intap1(p); //ok 2 *ap1 = 12; // 3 the first situation has called : explicit auto_ptr(_Ty *_Ptr = 0) _THROW0() the second : auto_ptr(auto_ptr_ref<_Ty_Right) _THROW0()
11
2394
by: subramanian100in | last post by:
Suppose we have a class named Test. Test obj; // assuming default ctor is available Test direct_init(obj); // direct initialization happens here Test copy_init = obj; // copy initialization happens here Suppose we have a function void fn(Test arg);
15
7844
by: akomiakov | last post by:
Is there a technical reason why one can't initialize a cost static non- integral data member in a class?
7
1518
by: krishna | last post by:
What is the need of this syntax for initializing values, isn't this ambiguous to function call? e.g., int func_name(20); this looks like function call (of course not totally as there is no function body), but is declaration and initialization of an integer variable 'func_name', is it step towards completeness of OOP abstraction in the...
0
7462
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7730
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7975
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7492
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7823
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5101
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3510
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3491
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1069
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.