473,804 Members | 2,261 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

evaluated function defaults: stored where?

Default parameter values are evaluated once when the function definition is
executed.
Where are they stored? (A guess: in a dictionary local to the function.)
Where is this documented?

As a Python newbie I found this behavior quite surprising.
Is it common in many other languages?
Is it unsurprising if I look at it right?

Thanks,
Alan Isaac
Jul 19 '05 #1
6 1477
[Alan Isaac]
Default parameter values are evaluated once when the function definition is
executed. Where are they stored?
def f(a, b=10, c=20): .. pass f.func_defaults

(10, 20)

Where is this documented?


http://docs.python.org/ref/types.html#l2h-78

Raymond Hettinger

Jul 19 '05 #2
David Isaac wrote:
As a Python newbie I found this behavior quite surprising.


It can be even more surprising if a default value is mutable:
def foo(a, b=[]): .... b.append(a)
.... return b
foo(3,[1,2]) [1, 2, 3]
foo('c',['a','b']) ['a', 'b', 'c']
foo(1) [1]

So far, everything is behaving much as you'd expect, but then:
foo(2) [1, 2]
foo(3) [1, 2, 3]

The parameter is bound to the list at creation time and, being mutable,
is modifiable each time the function is called.

This can be avoided by modifying your function slightly:
foo(3, [1,2]) [1, 2, 3]
foo('c', ['a','b']) ['a', 'b', 'c']
foo(1) [1]
foo(2) [2]
foo(3)

[3]

-alex23

Jul 19 '05 #3
I wrote: (some guff on default parameters)

Of course, it helps if I actually include the alternative function's
code:
def foo(a, b = None):

.... if b == None: b = []
.... b.append(a)
.... return b

Sorry about that :)

-alex23

Jul 19 '05 #4
David Isaac wrote:
Default parameter values are evaluated once when the function definition is
executed.
Where are they stored?
A good bet for where to start looking for the storage would be as an
attribute of the function object. From this point, there are two paths:

(a) Make a function and inspect it:
def fun(a,b=42,c=66 6): .... pass
.... dir(fun) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__',
'__get__', '__getattribute __', '__hash__', '__init__', '__module__',
'__name__', '__new__', '__reduce__', '__reduce_ex__' , '__repr__',
'__setattr__', '__str__', 'func_closure', 'func_code', 'func_defa
ults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] fun.func_defaul ts (42, 666)

(b) Become familiar with the general structure of the manuals.
By process of elimination, the Python Reference Manual would be a good
place to start for a question of this type.
Inside that manual, this is a likely candidate:
"""
3.2 The standard type hierarchy
Below is a list of the types that are built into Python.
"""

I'll leave you to read further ...
(A guess: in a dictionary local to the function.)
As you've seen the default values are contained in a tuple. So where are
the keys of the mapping {'b': 42, 'c': 666} that you expected? Suppose
*you* do the extra research and report back ...
Where is this documented?
See above.

As a Python newbie I found this behavior quite surprising.
Surprisingly good, bad or just different? Do you have alternate
non-surprising behaviours in mind?
Is it common in many other languages?
That makes two of us who don't know and haven't done any research :-)
My impression based on a limited number of different languages that I've
worked with or looked at is that Python's apparatus is the best I've
seen; YMMV.
Is it unsurprising if I look at it right?


Yes; in general this is true across many domains for a very large number
of referents of "it" :-)

Cheers,
John
Jul 19 '05 #5
> > Is it unsurprising if I look at it right?

[John Machin's QOTW]
Yes; in general this is true across many domains for a very large number
of referents of "it" :-)


There's a Quote of the Week in there somewhere.

Jul 19 '05 #6
Alan Isaac wrote:
Default parameter values are evaluated once when the function definition is executed. Where are they stored? ... Where is this documented?


Forgive any poor phrasing: I'm not a computer science type.
At http://www.network-theory.co.uk/docs/pytut/tut_26.html we read:
"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 global symbol table, and then in the table of
built-in names."

But the default values of function parameters seem rather like a static
attributes of a class.
Is that a good way to think of them?
If so, are they somehow accessible?
How? Under what name?

Thanks,
Alan Isaac
Jul 19 '05 #7

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

Similar topics

5
1788
by: Heinz | last post by:
Hi there Out of curiosity .... Long time ago I was working with Infomix (now IBM) Universal Server, that had a data type 'html' implemented as data blade. Through data blades you could extend the sql engine with your own data types. Can't remember exactly how it worked but you could store html with embedded 'sql code' in the database.
9
4967
by: Penn Markham | last post by:
Hello all, I am writing a script where I need to use the system() function to call htpasswd. I can do this just fine on the command line...works great (see attached file, test.php). When my webserver runs that part of the script (see attached file, snippet.php), though, it doesn't go through. I don't get an error message or anything...it just returns a "1" (whereas it should return a "0") as far as I can tell. I have read the PHP...
8
2804
by: Nick Coghlan | last post by:
Time for another random syntax idea. . . So, I was tinkering in the interactive interpreter, and came up with the following one-size-fits-most default argument hack: Py> x = 1 Py> def _build_used(): .... y = x + 1 .... return x, y ....
39
7890
by: | last post by:
I am trying to run the following agregate function in a parameterized query on Access2000: Min(.*sqr(./.)/) The query saved OK, but an attempt to run it results in the message: The expression is typed incorrectly or it is too complex to be evaluated If the sintax correct? Perhaps it is, otherwise it would not save. What can be done about it?
5
2802
by: steve | last post by:
Hi, When I copy tables in a database from one server to another using enterprise manager, everything copies ok, except for field defaults. Has anyone seen this, and what is the solution? -- http://www.dbForumz.com/ This article was posted by author's request Articles individually checked for conformance to usenet standards Topic URL:...
3
2541
by: Gary Besta | last post by:
I am trying to add a simple case statement to a stored procedure or user defined function. However when I try and save the function/procedure I get 2 syntax errors. Running the query in query analyser works fine and a result is given with no syntax errors. I believe its something to do with the spaces in the field names. Not my choice as its an existing system I have to work around. Any help greatly appreciated SQL Query
12
9550
by: Newbie | last post by:
how can i call an oracle function to get data without using a select statement or stored procedures? given a project_no, i need to call the function: ops$sqltime.pa_new_job_no_fn which will return the next job_no thanks in advance.
45
2484
by: madhawi | last post by:
Is it better to use a macro or a function?
7
7075
by: jamesclose | last post by:
My problem is this (apologies if this is a little long ... hang in there): I can define a function in VB.NET with optional parameters that wraps a SQL procedure: Sub Test(Optional ByVal Arg1 As Integer = 0, _ Optional ByVal Arg2 As Integer = 0, _ Optional ByVal Arg3 As Integer = 0) ' Call my SQL proc with the same signature
0
9714
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10600
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10350
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10096
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9174
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6866
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3834
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3002
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.