473,761 Members | 9,480 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Accessing Function Variables from Sub-functions

On Apr 14 2003, 10:30 pm, Alex Martelli <al...@aleax.it wrote:
Sebastian Wilhelmi wrote:
Hi,
I would like to do the following:
-------8<-------8<-------8<-------8<-------
def test ():
count = 0
def inc_count ():
count += 1
inc_count ()
inc_count ()
print count
test ()
-------8<-------8<-------8<-------8<-------
This doesn't work (and I even understand, why ;-)

Specifically: a nested function cannot *RE-BIND* a variable of
an outer function.
Sorry to dig up this old thread, but I would like to know what's the
rationale is. Why can't a nested function rebind a variable of an
outer function?
>
One solution is the following, which I however do not see as very
clean or nice.
-------8<-------8<-------8<-------8<-------
def test ():
count = [0]
def inc_count ():
count[0] += 1
inc_count ()
inc_count ()
print count[0]
test ()
-------8<-------8<-------8<-------8<-------
Now my question: Is there some way to achieve this with a nicer
syntax?

Depends on your tastes in syntax, e.g.:

def test():
class Bunch: pass
loc = Bunch()
loc.count = 0
def inc_count():
loc.count += 1
inc_count()
inc_count()
print loc.count

or:

def test():
test.count = 0
def inc_count():
test.count += 1
inc_count()
inc_count()
print test.count

and no doubt quite a few others.
I was trying to write a function that creates another function and
returns it when I came across this problem. These two solutions have a
difference:

def M():
M.c = 0
class Bunch:
pass
Bunch.c = 0
def f():
M.c += 1
Bunch.c += 1
print M.c, Bunch.c
return f
>>>f = M()
f2 = M()
f()
1 1
>>f()
2 2
>>f()
3 3
>>f2()
4 1
>>f2()
5 2
>>f2()
6 3

The created functions share their variables binded to the outer
function, but have their separate copies of variables bundled in a
class.

Is binding name to the function object a python way to use 'static'
variables? But how to initialize them?
>
Using 'global' would not count, as that would make a variable
unnecessarily known to the outside.

The two solutions above outlined differ in this respect -- variable
'loc' in the former is local to function test, while function attribute
test.count in the latter is "known to the outside" (it survives each
execution of test and can be examined "from the outside").

Class Bunch (or some highly refined version thereof) IS typically
around whenever I program, see for example:

http://mail.python.org/pipermail/pyt...ly/112007.html

for a typical presentation. Having available the MetaBunch there
described, I'd start the function as follows:

def test():
class Bunch(MetaBunch ): count=0
loc = MetaBunch()
def inc_count():
loc.count += 1

etc. I do find such constructs often handy...

Alex
Oct 11 '07 #1
2 2555
Licheng Fang wrote:
On Apr 14 2003, 10:30 pm, Alex Martelli <al...@aleax.it wrote:
>Sebastian Wilhelmi wrote:
Hi,
I would like to do the following:
-------8<-------8<-------8<-------8<-------
def test ():
count = 0
def inc_count ():
count += 1
inc_count ()
inc_count ()
print count
test ()
-------8<-------8<-------8<-------8<-------
This doesn't work (and I even understand, why ;-)

Specifically : a nested function cannot *RE-BIND* a variable of
an outer function.

Sorry to dig up this old thread, but I would like to know what's the
rationale is. Why can't a nested function rebind a variable of an
outer function?
Because the lack of variable declarations in python makes the
left-hand-side-appearance of a variable the exact distinction criteria
between inner and outer scopes. Thus it can't rebind them. What you can do
is to use mutables as container for outer variables:
def outer():
v =[1]
def increment():
a = v[0]
a += 1
v[0] = a
increment()
print v[0]
Diez
Oct 11 '07 #2

"Licheng Fang" <fa*********@gm ail.comwrote in message
news:11******** **************@ o3g2000hsb.goog legroups.com...
| Sorry to dig up this old thread, but I would like to know what's the
| rationale is. Why can't a nested function rebind a variable of an
| outer function?

Because it is debateble whether this is overall a good idea and because it
was not obvious exactly how to do so. (There were about 10 different
proposals.) I believe an addition is scheduled for 3.0 (and 2.6 I
suspect).

Oct 11 '07 #3

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

Similar topics

2
1499
by: Matt Smolic | last post by:
02.06.04 I need some help displaying a public variable on a form. The variable is declared and initilazied in a module at startup (and declared Public). I have verified this with a msgBox(dbprogram) call. When I try to display it in the form in a text box I get a #Name? error instead. I was told I have to write a function to display it. I wrote a public function in the startup module to return the value of a given string variable. Below...
0
1577
by: N. Demos | last post by:
Hello, I'm having problems accessing a complex XML child node (latitude & longitude), and passing it to a function when the XML file has been read into a DataSet. Specifically, the returned object from accessing the 'latitude' and 'longitude' nodes is not a DataTable (as specified in the MSDN). I'm not sure what type is being returned, nor how to go about finding out. Any pointers would be appreciated. Below is the relevent Error message,...
9
4813
by: Blake Weaver | last post by:
Ok, this is probably a no-brainer for most of you but its escaping me and I can't even seem to find the answer in any documentation. How do you access a friend variable of one class, from another class in the same project? Thanks Blake
9
3688
by: Joel Moore | last post by:
I'm a little confused here. If I have the following: Public ClassA Friend varA As Integer Private varB As Integer Private ClassB Public Sub MethodA() ' How can I access varA and varB here? End Sub
3
2031
by: Sam Learner | last post by:
Hello everyone, I am developping an application, I create a thread for the application because it is about to download a large file, and wanted it to do it inside of a thread... Now, the function I need the thread to call has a parameter... How do I call a function with the addressof(..) with a parameter value? for example: public function processData(byval data as arraylist) as boolean.... ....
8
2745
by: dwok | last post by:
I have been wondering this for a while now. Suppose I have a class that contains some private member variables. How should I access the variables throughout the class? Should I use properties that expose the variables or is it OK to just access the variables directly? Keep in mind that I am talking about accessing the variables from within the class that they are defined. Thanks!
12
11719
by: Steve Blinkhorn | last post by:
Does anyone know of a way of accessing and modifying variables declared static within a function from outside that function? Please no homilies on why it's bad practice: the context is very particular and involves automatically generated code. I know several other ways of attacking my problem, but this would be the cleanest if it could be made to work. A little more context. I use C as the output of a code generating system which...
5
5867
by: MrJim | last post by:
How should variables be declared and referenced in both the base and derived form so they can be accessed?
2
2132
by: GCM | last post by:
I have a database which was created from another parent database by combining some fields into one field for clerification purposes. When I create a for with the following command I get this error: Error accessing file. Network connection may have been lost. Following is the function I use. Eveything else works fine. This function worked on the parent database. The form data is linked to the proper table: ...
1
1230
by: priyamtheone | last post by:
Hi friends, I have got two problems while accessing cd drives. FIRSTLY: I want a code example of how to detect whether the cd drive of my machine is opened or closed. SECONDLY: I'm trying to open or close the cd drive of my machine. It's working properly if there's only one cd drive. But wut if there r more than one. The code I'm using is accessing the default cd drive only. Below is the code I'm using: 'In the general declarations:...
0
9345
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
10115
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
9957
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
9905
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
9775
tracyyun
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...
0
8780
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...
0
5373
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3456
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2752
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.