473,856 Members | 1,569 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Optional parameter object re-used when instantiating multiple objects

Hello All,

Why is python designed so that b and c (according to code below)
actually share the same list object? It seems more natural to me that
each object would be created with a new list object in the points
variable.

class Blob:
def __init__(self, points=[]):
self._points = points
b = Blob()
c = Blob()

b._points.appen d(1)
c._points.appen d(2)

print b._points

# this will show that b._points is the same object as c._points



Nov 15 '08
35 1998
On Nov 16, 8:16*pm, Aaron Brady <castiro...@gma il.comwrote:
On Nov 16, 12:52*am, Steven D'Aprano <st...@REMOVE-THIS-
I've given practical reasons why the
Python choice is better. If you want default argument to be created from
scratch when the function is called, you can get it with little
inconvenience, but the opposite isn't true. It is very difficult to get
static default arguments given a hypothetical Python where default
arguments are created from scratch. There's no simple, easy idiom that
will work. The best I can come up with is a convention:

I'm not so sure.

## Default evaluated at definition time. *(Current.)

# Static arg.
def f( a= [] ):
* ...

# Non-static arg.
def f( a= None ):
* if a is None: a= []
Oops. Forgot one, after the subsequent posts.

# Non-static arg.
@nonstatic( a= list )
def f( a ):
...

This can achieve the 'if a is None' effect. 'nonstatic' takes a
callable or a string, '@nonstatic( a= "[]" )'.

I don't see a way to achieve George Sakkis's example:

if y is None: y = x*x
if z is None: z = x+y

Without a change to the language (the other options don't need one).

#emulates 'def foo(x, y=`x*x`, z=`x+y`):'
@nonstatic( y= 'x*x' ) #illegal
@nonstatic( z= 'x+y' ) #illegal
def foo(x, y, z):
return x+y+z
Nov 17 '08 #21
Thanks to all for your replies

All things considered, I vote for evaluating the arguments at runtime
(each time the function is called). Good reasons for this have already
been mentioned so I won't repeat them. A programming language is a
user interface of sorts. (Pretty much all languages are logical so
"correctnes s" is not what I'm meaning to discuss - I'm thinking about
usability.) Python provides, for the most part, an *excellent* user
interface to the programmer. Why not make it even "better" by
evaluating the arguments each time the function is called? It will be
harder to change the language 10 years from now, so why not change it
now?

(By "better" I mean that over many years of time programmers will be
more productive because the language will be learned a bit faster with
a fewer surprises - and still retain its power.)

-Rick

On Nov 16, 10:28 pm, "Chris Rebert" <c...@rebertia. comwrote:
For the Nth time this year that this has come up, I'll point out yet
again that this issue has already been discussed to death before:

[Python-ideas] proto-PEP: Fixing Non-constant Default Argumentshttp://mail.python.org/pipermail/python-ideas/2007-January/000121.html

[Python-3000] pre-PEP: Default Argument Expressionshttp ://mail.python.org/pipermail/python-3000/2007-February/005704.html

Result: Evaluating the arguments at runtime rather than
definition-time was deemed too magical; the backward compatibility
issues make changes unlikely; it's hard to find an acceptable syntax.

But hey, if some people want to have another go at it, best of luck.

Cheers,
Chris
--
Follow the path of the Iguana...http://rebertia.com

On Sun, Nov 16, 2008 at 8:11 PM, alex23 <wuwe...@gmail. comwrote:
On Nov 17, 12:27 pm, Steve Holden <st...@holdenwe b.comwrote:
If multiple statements are needed to perform the
argument initialization, how would you then propose the problem should
be solved?
Why, with another function of course!
def f(x, y=`f_arg_comput ation(x)`): ...
Or my personal favourite:
def f(x, **`f_arg_comput ation(x)`): ...
Seriously, though, I agree with Steve; the function body -is- the
place for computation to occur.
--
http://mail.python.org/mailman/listinfo/python-list
Nov 19 '08 #22
On Nov 19, 8:41*am, Rick Giuly <rgiuly.gr...@y ahoo.comwrote:
Python provides, for the most part, an *excellent* user
interface to the programmer. Why not make it even "better"
by evaluating the arguments each time the function is called?
It will be harder to change the language 10 years from now,
so why not change it now?
You probably messed up with your time machine; "now" is 2008, not
1991 ;-)

George
Nov 19 '08 #23
On Nov 19, 12:05*pm, Dennis Lee Bieber <wlfr...@ix.net com.comwrote:
>
* * * * I wouldn't expect a language like Ada to somehow re-evaluate a
default argument on each call; why would I expect Python to do such?
Lots of people do.

If you had a menu in a browser interface that had the items, say,
'Stop' and 'Reload', what would you expect to happen if you clicked on
them?
Nov 20 '08 #24
On Nov 20, 10:14*am, Aaron Brady <castiro...@gma il.comwrote:
If you had a menu in a browser interface that had the items, say,
'Stop' and 'Reload', what would you expect to happen if you clicked on
them?
If you had a keyword called 'def', which defined functions, would you
expect it to define said functions when it executed, or on each
function call?
Nov 20 '08 #25
On Nov 19, 7:58*pm, alex23 <wuwe...@gmail. comwrote:
On Nov 20, 10:14*am, Aaron Brady <castiro...@gma il.comwrote:
If you had a menu in a browser interface that had the items, say,
'Stop' and 'Reload', what would you expect to happen if you clicked on
them?

If you had a keyword called 'def', which defined functions, would you
expect it to define said functions when it executed, or on each
function call?
At first, I would expect it to define them at compile-time. Then,
when I learned there was no such thing, I would expect it to define
them at execute-time. What does that have to do with evaluating a
default argument?
Nov 20 '08 #26
On Nov 20, 10:42*pm, Aaron Brady <castiro...@gma il.comwrote:
At first, I would expect it to define them at compile-time. *Then,
when I learned there was no such thing, I would expect it to define
them at execute-time. *What does that have to do with evaluating a
default argument?
It has -everything- to do with it when we're talking about the
defining of functions, and certainly a lot more relevance than straw
man arguments on the behaviour of browser buttons.

You said that you "would expect it to define them at execute-time". So
is that when the interpreter first hits the def or when the
interpreter hits every single function call? Because I personally
consider it to clearly occur at the point of definition and not at the
point of calling.
Nov 20 '08 #27
On Nov 20, 5:54*pm, alex23 <wuwe...@gmail. comwrote:
On Nov 20, 10:42*pm, Aaron Brady <castiro...@gma il.comwrote:
At first, I would expect it to define them at compile-time. *Then,
when I learned there was no such thing, I would expect it to define
them at execute-time. *What does that have to do with evaluating a
default argument?

It has -everything- to do with it when we're talking about the
defining of functions, and certainly a lot more relevance than straw
man arguments on the behaviour of browser buttons.

You said that you "would expect it to define them at execute-time". So
is that when the interpreter first hits the def or when the
interpreter hits every single function call? Because I personally
consider it to clearly occur at the point of definition and not at the
point of calling.
Why, I would expect the interpreter to define the functions when it
first hits the def, that is, at the point of definition.
Nov 21 '08 #28
On Wed, 19 Nov 2008 10:05:23 -0800, Dennis Lee Bieber wrote:
Do you really want a "default" argument that changes value depending
upon actions performed in the /surrounding/ scope?
And if you do, it is easy to get:

default_y = "something"

def parrot(x, y=None):
if y is None:
y = default_y
--
Steven
Nov 21 '08 #29
On Wed, 19 Nov 2008 11:26:54 -0800, George Sakkis wrote:
On Nov 19, 1:05Â*pm, Dennis Lee Bieber <wlfr...@ix.net com.comwrote:
>On Wed, 19 Nov 2008 05:41:57 -0800 (PST), Rick Giuly
<rgiuly.gr...@ yahoo.comdeclai med the following in comp.lang.pytho n:
(By "better" I mean that over many years of time programmers will be
more productive because the language will be learned a bit faster
with a fewer surprises - and still retain its power.)

Â* Â* Â* Â* Your opinion... I'm sure there are some libraries out there
Â* Â* Â* Â* that
rely upon the current behavior

That's a straw man; of course they rely on it since they can. The same
would be even more true if the opposite behavior was selected from the
beginning, many more libraries would rely on it instead of (ab)using
None as default.
"Many more"? You're guessing. By memory, most uses in the standard
library for default values either use immutables (strings or ints), in
which case rebinding the default at runtime is irrelevant, or are using
None to trigger special behaviour. (Please feel free to go through the
std lib and verify my feeble memories.) The *specific* gotcha people are
complaining about only affects a tiny proportion of default values: in
practice, it is almost always either [] or {}.

It seems a waste to have Python pay the cost of re-evaluating all those
default=0 and default=None calls just to satisfy a small proportion of
users whose intuition about Python's behaviour happens to be wrong. Since
that intuition has real costs and the current behaviour has real
benefits, people should just learn the Python way.

(I'm sympathetic for requests for syntactic sugar to get runtime
evaluation of defaults. I'm not sympathetic at all for requests to change
the default behaviour.)
That's the only argument that may worth some merit. It's interesting
though that C++, a language much more obsessed with performance, picks
the runtime semantics:
You're not going to hold C++ up as a shining beacon of the right way to
do things, are you?

--
Steven
Nov 21 '08 #30

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

Similar topics

3
4350
by: Rane Bowen | last post by:
Hi, I am using python with a makepy generated wrapper on a COM application. One of this object's methods has 3 parameters, two of which are optional. If I call the method with just the non-optional parameter, or all three parameters, it works. If I call it with the first two parameters, I get the following error: (-2147352567, 'Exception occurred.', (0, 'Amphora.Session.1', 'A bad parameter was passed to the method', None, 0,...
7
36609
by: JT | last post by:
how can i declare a function that will accept an optional parameter? something like: function newFunc(strValue1, strValue2) --where strValue2 is optional. thanks much.
6
2149
by: spammy | last post by:
Hi all, Im attempting to use a COM class in C# via .NET interop. The class has two modes - synhrounous and asynchronous. The mode is determined by the use (or not) of an optional out parameter: COMClass test = new COMClass(); object results = null;
6
2624
by: Otto Wyss | last post by:
I've the following function declaration: wxTree GetLastChild (const wxTree& item, long& cookie) const; I'd like to make the cookie parameter optional, i.e. "long& cookie = ....", without breaking any software using the old API. The implementation looks like wxTree wxTreeListMainWindow::GetLastChild (const wxTree& item, long& cookie) const {
13
2526
by: William Ryan | last post by:
I just picked up a copy of John Robbins' debugging book and started to look at disassembled code. Anyway, I hate optional Parameters in VB, but I was checking them out to see what IL is created. I've done this before with Modules, and saw that <gasp> they behave just like sealed classes with only static members. Anyway, it looks like Optional Parameters are nothing but a way to tell the compiler to write some overloads for you. So, in...
4
3795
by: Yong Jiang | last post by:
I am trying to convert some vb code calling COM oboject methods to C#. Example shown as follows Dim Stream As New ADODB.Stream Call Stream.Open() Stream.Open has three optional parameters. I am trying to convert it to C# as shown as follows ADODB.Stream Stream = null;
1
2052
by: Hanover | last post by:
In at typical SQL command if I want an optional parameter, I say "Where ID=@ID or @ID=Null" This way if I dont pass in a parameter, it will just pull all of the IDs. Is there a way to set this up in the text command of a SQLCommand object in .NET?
2
11958
by: Oenone | last post by:
In our applications, we use the special value of DateTime.MinValue to represent "null dates" throughout all our code. We recently ran into an issue where we wanted an optional date parameter for a procedure. We weren't able to declare it with DateTime.MinValue as its default value, as MinValue is a read-only property rather than a constant. To work around, we had to use a "magic date" that we checked for later on. I was never very happy...
7
13478
by: Sam Shrefler | last post by:
I'm working on creating a WebService / WebMethod to receive a record in real time from another system. The record contains about 20 fields. 10 of which aren't required. I was planning on just making a method with 20 parameters. But, I see there is no way to make an "optional" c# parameter. I was just wondering if anyone had an suggestions on how to implement this? The parameters are all different primitive types (int, string,...
9
3883
by: =?Utf-8?B?V2ViQnVpbGRlcjQ1MQ==?= | last post by:
I'll ask, how do you do it? -- (i''ll be asking a lot of these, but I find C# totally way cooler than vb and there''s no go''n back!!!) thanks (as always) kes
0
9765
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,...
0
11065
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
10700
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...
1
10795
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,...
0
9536
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...
1
7934
isladogs
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...
0
5962
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4581
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
3
3203
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.