473,757 Members | 2,320 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

function parameter scope python 2.5.2


I recently encountered some interesting behaviour that looks like a bug
to me, but I can't find the appropriate reference to any specifications
to clarify whether it is a bug.

Here's the example code to demonstrate the issue:

class SomeObject(obje ct):

def __init__(self):
self.words = ['one', 'two', 'three', 'four', 'five']

def main(self):
recursive_func( self.words)
print self.words

def recursive_func( words):
if len(words) 0:
word = words.pop()
print "Popped: %s" % word
recursive_func( words)
else:
print "Done"

if __name__ == '__main__':
weird_obj = SomeObject()
weird_obj.main( )
The output is:

Popped: five
Popped: four
Popped: three
Popped: two
Popped: one
Done
[]

Of course I expected that recursive_func( ) would receive a copy of
weird_obj.words but it appears to happily modify the object.

Of course a work around is to explicitly create a copy of the object
property befor passing it to recursive_func, but if it's used more than
once inside various parts of the class that could get messy.

Any thoughts? Am I crazy and this is supposed to be the way python works?
Nov 20 '08
11 1973
Peter Pearson <pp******@nowhe re.invalidwrite s:
On Fri, 21 Nov 2008 10:12:08 -0500, J Kenneth King wrote:
>Steven D'Aprano <st***@REMOVE-THIS-cybersource.com .auwrites:
>>>
I am curious why you thought that. What made you think Python should/did
make a copy of weird_obj.words when you pass it to a function?
[snip]
>Of course if there is any further reading on the subject, I'd appreciate
some links.

As one relatively new Python fan to another, I recommend following
this newsgroup. Many important aspects of Python that several books
failed to drive through my skull are very clearly (and repeatedly)
explained here. Hang around for a week, paying attention to posts
with subjects like "Error in Python subscripts" (made-up example),
and curse me if you don't find it greatly rewarding.
I do lurk more often than I post and sometimes I help out people new to
Python or new to programming in general. I know how helpful usenet can
be and usually this group in particular is quite special. It's good
advice to read before you post; quite often the question has been
proposed and answered long before it came to your little head (not you
in particular; just general "you").

In this case, I was simply lacking the terminology to find what I was
looking for on the subject. In such cases turning to the community seems
like a fairly reasonable way to find clarification. I've only been
programming in Python specifically for two years or so now, so I hope I
can be forgiven.

Cheers.
Nov 21 '08 #11
J Kenneth King wrote:
I was working on a program of some complexity recently and quickly
caught the issue in my tests. I knew what was going on and fixed it
expediently, but the behaviour confused me and I couldn't find any
technical documentation on it so I figured I just didn't know what it
was referred to in Python. Hence the post. :)
Language Reference / Expressions / Primaries / Calls +
Language Reference / Compound statements / Function definitions

Hmm. Read by themselves, these are not as clear as they could be that
what parameters get bound to are the argument objects. One really needs
to have read the section on assignment statements first.

Nov 21 '08 #12

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

Similar topics

3
14946
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) { document.images.src = eval("mt" +menu+ ".src") } alert("imgOff_hidemenu"); hideMenu=setTimeout('Hide(menu,num)',500);
20
1995
by: Gregory Piñero | last post by:
Hey guys, would someone mind giving me a quick rundown of how references work in Python when passing arguments into functions? The code below should highlight my specific confusion: <code> bool1=True lst1= def func1(arg1): arg1.append(4)
2
3002
by: FAN | last post by:
I want to define some function in python script dynamicly and call them later, but I get some problem. I have tried the following: ################################## # code ################################## class test: def __init__(self): exec("def dfunc(msg):\n\tprint msg\nprint 'exec def function'") dfunc('Msg in init ...') # it work
38
2777
by: Lasse Vågsæther Karlsen | last post by:
After working through a fair number of the challenges at www.mathschallenge.net, I noticed that some long-running functions can be helped *a lot* by caching their function results and retrieving from cache instead of calculating again. This means that often I can use a natural recursive implementation instead of unwinding the recursive calls to avoid big exponential running-times. Ok, so I thought, how about creating a decorator that...
5
1327
by: Martin Johansen | last post by:
Hello C programmers If I have a function, say void f(int a, char b); And I call this function with the following arguments char a; int b;
16
1653
by: Rob Somers | last post by:
Say I have the following code: void foo(int some_int); ..... int x = 5; foo(x); ..... void foo(int some_int) {
7
1876
by: Csaba Gabor | last post by:
I feel like it's the twilight zone here as several seemingly trivial questions are bugging me. The first of the following three lines is a syntax error, while the last one is the only one that shows the alert. What is the essential reason? function () { alert('hi mom'); }(); function () { alert('hi dad'); }(8); var x=function () { alert('hi bro'); }();
78
4968
by: Josiah Manson | last post by:
I found that I was repeating the same couple of lines over and over in a function and decided to split those lines into a nested function after copying one too many minor changes all over. The only problem is that my little helper function doesn't work! It claims that a variable doesn't exist. If I move the variable declaration, it finds the variable, but can't change it. Declaring the variable global in the nested function doesn't work...
4
2496
by: Tony Lownds | last post by:
(Note: PEPs in the 3xxx number range are intended for Python 3000) PEP: 3107 Title: Function Annotations Version: $Revision: 53169 $ Last-Modified: $Date: 2006-12-27 20:59:16 -0800 (Wed, 27 Dec 2006) $ Author: Collin Winter <collinw@gmail.com>, Tony Lownds <tony@lownds.com> Status: Draft Type: Standards Track
11
1601
by: =?iso-8859-1?q?Erik_Wikstr=F6m?= | last post by:
struct foo { int i; }; int bar(foo& f) { return f.i++; } int main() { bar(foo());
0
9487
marktang
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...
0
9297
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
10069
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
8736
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
7285
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
6556
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();...
0
5324
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3395
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2697
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.