Common list in distinct objects'
Duncan Booth
duncan at NOSPAMrcp.co.uk
Wed Jul 17 05:00:20 EDT 2002
otijim at yahoo.com (Jake R) wrote in news:3d3427bf.428996374 at news.byu.edu:
> I just wonder what is the preferred result. IMO each call should
> return a new and distinct list (to me this makes sense since in my
> case each call creates a new and distinct object. But other than PHP
> I have never used a language that allows default parameter values so
> maybe this is an already established standard that I'm not familiar
> with.
>
Not a standard, AFAIR C++ gets around the issue by requiring default
arguments to be constant expressions. Likewise Visual Basic requires
default arguments to be constants (effectively strings, numbers or Empty).
I think that the important thing is to remember that in Python 'def' is a
statement executed at runtime. In effect:
def myFunction(a, b=something):
...
is the same as an assignment statement:
myFunction = new.function(<code>, globals(), 'myFunction', (something,))
This opens up a whole host of possibilities that simply aren't present in
more static languages. For example you could put the 'def' inside a for
loop and create a list of functions:
adders = []
for i in range(100):
def adder(x, increment=i): return x+increment
adders.append(adder)
To be able to do this, the default arguments simply have to be evaluated
when the 'def' is executed, in the scope where the def is executed. That
'scope' issue is important as well:
def fn(x=x+1): pass
The 'x' in the default argument is the variable 'x' in scope when the
function is defined, not the parameter 'x'. There is a tradeoff here,
sometime you might want a default value to depend on another parameter and
as with your list, the only way to do this is to put in a placeholder value
and test for it. e.g. I want two arguments and the second one is usually
twice the first:
def fn(x, y=2*x): # doesn't work, looks for 'x' outside the function.
def fn(x, y=None):
if y is None: y = 2*x
As I said, the way I look at this is to always remember that 'def' is
executed at runtime and the default values are evaluated when 'def'
executes. 'class' and its baseclasses are similar, except that the body of
the class statement is also executed when the class is defined, whereas the
body of the function doesn't execute until called.
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list