evaluated function defaults: stored where?
John Machin
sjmachin at lexicon.net
Thu May 26 02:33:25 EDT 2005
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=666):
... 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_defaults
(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
More information about the Python-list
mailing list