Can anyone explain the behaviour of python when running this script? def method(n, bits=[]):
.... bits.append(n)
.... print bits
.... method(1)
[1] method(2)
[1, 2]
It's the same in python 1.5, 2.3 and 2.4 so it's not a bug. But I
expected the variable "bits" to be re-initialised to an empty list as
each method was called. Whenever I explain optional keyword arguments
to someone I have usually (wrongly as it turns out) said it is
equivalent to:
def method(n, bits=None):
.... if bits is None:
.... bits=[]
.... bits.append(n)
.... print bits
.... method(1)
[1] method(2)
[2]
Is there a good reason why these scripts are not the same? I can
understand how/why they are different, it's just not what I expected.
(It seems strange to me that the result of the first method can only be
determined if you know how many times it has already been called)
Is this behaviour what you would (should?) intuitively expect?
Thanks,
Brian 24 2038 br********@secu retrading.com wrote: Can anyone explain the behaviour of python when running this script?
(...) Is there a good reason why these scripts are not the same? I can understand how/why they are different, it's just not what I expected. (It seems strange to me that the result of the first method can only be determined if you know how many times it has already been called)
see "python gotchas":
<http://www.ferg.org/projects/python_gotchas. html#bct_sec_5>
bye.
--
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
<#me> a foaf:Person ; foaf:nick "deelan" ;
foaf:weblog <http://www.netspyke.co m/> .
wrote: Can anyone explain the behaviour of python when running this script?
def method(n, bits=[]): ... bits.append(n) ... print bits ... method(1) [1] method(2)
[1, 2]
It's the same in python 1.5, 2.3 and 2.4 so it's not a bug. But I expected the variable "bits" to be re-initialised to an empty list as each method was called. Whenever I explain optional keyword arguments to someone I have usually (wrongly as it turns out) said it is equivalent to:
<snipped erroneous comparison>
No, it is closer to:
# Assume you have done this earlier:
import new
def _realmethod(n, bits):
bits.append(n)
print bits
# The def is roughly equivalent to this:
_defaultArgs = ([], )
method = new.function(_r ealmethod.func_ code, globals(), 'method',
_defaultArgs)
Each time you re-execute the def you get a new set of default arguments
evaluated, but the result of the evaluation is simply a value passed in to
the function constructor.
The code object is compiled earlier then def creates a new function object
from the code object, the global dictionary, the function name, and the
default arguments (and any closure as well, but its a bit harder to
illustrate that this way).
Thanks, this makes perfect sense. The phrase which sums it up neatly is
"Default parameter values are evaluated when the function definition is
executed"
However, is there a good reason why default parameters aren't evaluated
as the function is called? (apart from efficiency and backwards
compatibility)? Is this something that's likely to stay the same in
python3.0?
I'm really looking for a neat way to do the following:
def method(a,b,opt1 =None,opt2=None ,opt3="",opt4=N one):
if opt1 is None: opt1=[]
if opt2 is None: opt2={}
if opt4 is None: opt4=[]
Python syntax is normally so neat but this just looks a mess if there
are lots of parameters.
<br********@sec uretrading.com> wrote: However, is there a good reason why default parameters aren't evaluated as the function is called? (apart from efficiency and backwards compatibility)?
how would you handle this case:
def function(arg=ot herfunction(val ue)):
return arg
</F>
def function(arg=ot herfunction(val ue)):
return arg
My expectation would have been that otherfunction(v alue) would be
called if (and only if) the arg keyword parameter was missing from the
function() call (ie. the optional value is evaluated the lazy way).
Also, otherfunction would be called each and every time this function()
is called without the arg keyword. (At least, I would have assumed this
before today)
Still, I can see why it's been implemented the way it has, it just
seems a shame there isn't a neat shortcut to default lots of optional
arguments to new mutable objects. And since I'm not the only one to
fall into this trap it makes me wonder why the default behaviour isn't
made to be what most people seem to expect?
<br********@sec uretrading.com> wrote: def function(arg=ot herfunction(val ue)): return arg
My expectation would have been that otherfunction(v alue) would be called if (and only if) the arg keyword parameter was missing from the function() call (ie. the optional value is evaluated the lazy way).
what otherfunction? what value?
</F>
Hi,
I cannot see any strange behavior. this code works exacly as you and I
suspect: def otherfunction(x ) :
.... return x
.... def function(arg=ot herfunction(5)) :
.... return arg
.... function(3)
3 function()
5
Or is this not what you excepted?
- harold -
On 21.12.2004, at 15:47, br********@secu retrading.com wrote:
def function(arg=ot herfunction(val ue)): return arg
My expectation would have been that otherfunction(v alue) would be called if (and only if) the arg keyword parameter was missing from the function() call (ie. the optional value is evaluated the lazy way). Also, otherfunction would be called each and every time this function() is called without the arg keyword. (At least, I would have assumed this before today)
Still, I can see why it's been implemented the way it has, it just seems a shame there isn't a neat shortcut to default lots of optional arguments to new mutable objects. And since I'm not the only one to fall into this trap it makes me wonder why the default behaviour isn't made to be what most people seem to expect?
-- http://mail.python.org/mailman/listinfo/python-list
--
Freunde, nur Mut,
Lächelt und sprecht:
Die Menschen sind gut --
Bloß die Leute sind schlecht.
-- Erich Kästner
harold fellermann wrote: Hi,
I cannot see any strange behavior. this code works exacly as you and I suspect:
>>> def otherfunction(x ) : .... return x .... >>> def function(arg=ot herfunction(5)) : .... return arg .... >>> function(3) 3 >>> function()
5
Or is this not what you excepted?
Channelling the effbot, I think he was asking what namespace context you
expected the expression "arg=otherfunct ion(x)" to be evaluated in when
it's used at the time of a function call to dynamically create a new
default value for arg.
regards
Steve
--
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/
Holden Web LLC +1 703 861 4237 +1 800 494 3119 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Edward Diener |
last post by:
In the tutorial on functions there are sections on default arguments and
keyword arguments, yet I don't see the syntactic difference between them.
For default arguments the tutorial shows:
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
while for keyword arguments the tutorial shows:
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
|
by: Shao Zhang |
last post by:
Hi,
I am not sure if the virtual keyword for the derived classes are
required given
that the base class already declares it virtual.
class A
{
public:
virtual ~A();
|
by: spibou |
last post by:
What is strcmp supposed to return if one or both arguments passed to it
are NULL ?
|
by: matthewperpick |
last post by:
Check out this toy example that demonstrates some "strange" behaviour
with keyword arguments and inheritance.
=================================
class Parent:
def __init__(self, ary = ):
self.ary = ary
def append(self):
|
by: Matt |
last post by:
Hello. I'm having a very strange problem that I would like ot check
with you guys.
Basically whenever I insert the following line into my programme to
output the arguments being passed to the programme:
printf("\nCommand line arguement %d: %s.", i , argv );
The porgramme outputs 3 of the command line arguements, then gives a
segmentation fault on the next line, followed by other strange
| |
by: Armando Serrano Lombillo |
last post by:
Why does Python give an error when I try to do this:
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
len(object=)
TypeError: len() takes no keyword arguments
but not when I use a "normal" function:
return len(object)
|
by: Jasper |
last post by:
I'm stumped. I'm calling a method that has keyword args, but not
setting them, and yet one of them starts off with data?!
The class definition begins like so:
class BattleIntentionAction( BattleAction ):
def __init__( self, factionName, location, tactic='hold',
targetFacName='', terrainArgs=, garrisonIds= ):
self.terrainArgs = terrainArgs
print terrainArgs
|
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...
|
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...
|
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 most users, this new feature is actually very convenient. If you want to control the update process,...
|
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...
| |
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...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
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();...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |