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
Jul 18 '05
24 2041
Steven Bethard wrote: Fuzzyman wrote:Steven Bethard wrote: > >So, one of my really common use cases that takes advantage of the >fact that default parameters are evaluated at function definition >time: > >def foo(bar, baz, matcher=re.comp ile(r'...')): > ... > text = matcher.sub(r'. ..', text) > ... Sure.. but you also gave an example of an alternative that was
complex, Interesting. I would have thought that my example was pretty simple.
Maybe it would be helpful to generalize it to:
def foo(bar, baz, spam=badger(x, y, z)): ...
All it does is use a default value that was produced by a function
call. I'm surprised you haven't run into this situation before...
Of course, what is complex or simple is a matter of personal opinion.
I use this pattern so often that it's quite simple to me, but I guess I
can understand that if you don't use such a pattern, it might seem foreign to you.
Steve
Hello Steve,
It wasn't that part of the example that I thought was over complex.
(although it's not a 'pattern' I use often). You suggested that if we
had dynamic evaluation of default values, you would have to replace it
with : class foo(object): matcher=re.comp ile(r'...') def __new__(self, bar, baz, matcher=None): if matcher is None: matcher = self.matcher ... text = matcher.sub(r'. ..', text) ...
Now that I thought was over complex... when all you wanted to do was
put a constant into your default value !
Having said that I see Steve's point about not knowing the namespace
when the function will be called.
Regards,
Fuzzy http://www.voidspace.org.uk/python/index.shtml
<br********@sec uretrading.com> wrote:
... 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.
There's a decorator for that in the Cookbook (sorry, don't recall the
recipe number, but, it's on the site, and it got into the 2nd edition
which we're still expecting to have on paper at PyCon) -- basically
wrapping a function with a wrapper that does a copy.deepcopy on the
defaults values at each call (efficiency of course goes down the drain,
but you _did_ say "apart from efficiency"!-).
Alex
<br********@sec uretrading.com> wrote:
... the default params are evaluated at the definition. However, I still can't give a nice looking solution on how to re-write a function to have empty mutable values as default arguments: eg.
def method(a,b,opt1 =[],opt2=None,opt3 ="",opt4={})
How could I re-write this (especially if there are perhaps 20 optional parameters,any number of which may have mutable defaults) without writing 20 "if opt1 is None: opt1=[]" statements?
I don't have the recipe I mentioned at hand, but what about :
def makebrianhappy( f):
saved_defaults = f.func_defaults
def with_fresh_defa ults(*a, **k):
f.func_defaults = copy.deepcopy(s aved_defaults)
return f(*a, **k)
with_fresh_defa ults.__name__ = f.__name__
return with_fresh_defa ults
@ makebrianhappy
def method(a, b, opt1=[], opt2=None, opt3="", opt4={}):
...
I've added spaces after commas to make ME happy too (lack of such spaces
is my least favourite Python irritation;-), but I guess the semantics of
this (UNTESTED) code would work even without that;-).
Alex
Fuzzyman wrote: It wasn't that part of the example that I thought was over complex. (although it's not a 'pattern' I use often). You suggested that if we had dynamic evaluation of default values, you would have to replace it with :
>class foo(object): > matcher=re.comp ile(r'...') > def __new__(self, bar, baz, matcher=None): > if matcher is None: > matcher = self.matcher > ... > text = matcher.sub(r'. ..', text) > ...
Now that I thought was over complex... when all you wanted to do was put a constant into your default value !
Ahh. Yeah, the thing above is a bit complex, but it keeps the same
namespaces -- matcher is only available to foo, not the enclosing
class/module. Point taken of course. ;)
Steve 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: 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...
|
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
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: 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: 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: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |