472,965 Members | 2,472 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,965 software developers and data experts.

Globals in nested functions

def f():
a = 12
def g():
global a
if a < 14:
a=13
g()
return a

print f()

This function raises an error. Is there any way to access the a in f()
from inside g().

I could find few past discussions on this subject, I could not find
the simple answer whether it is possible to do this reference.

-
Suresh

Jun 21 '07 #1
4 1269
"jm*******@no.spam.gmail.com" <jm*******@gmail.comwrote:
def f():
a = 12
def g():
global a
if a < 14:
a=13
g()
return a

print f()

This function raises an error. Is there any way to access the a in f()
from inside g().

I could find few past discussions on this subject, I could not find
the simple answer whether it is possible to do this reference.
'global' means global to the module, it prevents the lookup happening in
current or nested scopes.

Simple answer:

You can access an object referenced by a nested scope variable and you
can mutate the object accessed in that way, but you cannot rebind the
name to a different object without resorting to hackery.

To get the effect you want, simply use a mutable object:
>>def f():
class v:
a = 12
def g():
if v.a < 14:
v.a=13
g()
return v.a
>>f()
13

and as soon as the code starts looking at all complex, refactor that so
the class is the thing you interact with:
>>class F(object):
def g(self):
if self.a < 14:
self.a = 13
def __call__(self):
self.a = 12
self.g()
return self.a
>>f = F()
f()
13
Jun 21 '07 #2
jm*******@no.spam.gmail.com wrote:
def f():
a = 12
def g():
global a
if a < 14:
a=13
g()
return a

print f()

This function raises an error. Is there any way to access the a in
f() from inside g().
Yes. Pass it to g when calling the latter and let g return the
result.

def f():
a = 12

def g(parm):
if parm < 14:
return 13
else:
return a

a = g(a)
return a

print f()

Strange refactoring though.

Regards,
Björn

--
BOFH excuse #400:

We are Microsoft. What you are experiencing is not a problem; it is
an undocumented feature.

Jun 21 '07 #3
jm*******@no.spam.gmail.com wrote:
def f():
a = 12
def g():
global a
if a < 14:
a=13
g()
return a

print f()

This function raises an error. Is there any way to access the a in f()
from inside g().

I could find few past discussions on this subject, I could not find
the simple answer whether it is possible to do this reference.

-
Suresh
As I'm struggling with this myself at the moment,
this will do the job:

def f():
global a
a = 12

cheers,
Stef Mientki
Jun 21 '07 #4
On 2007-06-21, jm*******@no.spam.gmail.com <jm*******@gmail.comwrote:
def f():
a = 12
def g():
global a
if a < 14:
a=13
g()
return a

print f()

This function raises an error. Is there any way to access the a
in f() from inside g().

I could find few past discussions on this subject, I could not
find the simple answer whether it is possible to do this
reference.
Python's scoping rules don't allow this. But you can 'box' the
value into a list and get the intended effect.

def f():
a = [12]
def g():
if a[0] < 14:
a[0] = 13
g()
return a[0]

You'll get better results, in Python, by using a class instances
instead of closures. Not that there's anything wrong with Python
closures, but the scoping rules make some fun tricks too tricky.

--
Neil Cerutti
Jun 21 '07 #5

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

Similar topics

10
by: lawrence | last post by:
I get the impression that most people who are using objects in their PHP projects are mixing them with procedural code. The design, I think, is one where the procedural code is the client code, and...
3
by: Robert Dodier | last post by:
Hello, I'm interested in introducing new variables into the environment of a Python interpreter or program. In reading through old posts to this newsgroup, I see there is an often-repeating...
6
by: Paddy | last post by:
Hi, I got tripped up on the way eval works with respect to modules and so wrote a test. It seems that a function carries around knowledge of the globals() present when it was defined. (The...
11
by: Matt | last post by:
Hello, I'm rather new to C++ and have a question about globals. What is the big deal about them? They make things much easier to program because you don't have to worry about all the passing...
2
by: DFS | last post by:
Not sure whether it's bad programming practice or not, but I have a module of globals I declare in each system: Global ws As Workspace Global db As Database Global td As TableDef Global rs As...
18
by: robert | last post by:
Using global variables in Python often raises chaos. Other languages use a clear prefix for globals. * you forget to declare a global * or you declare a global too much or in conflict * you...
17
by: meridian | last post by:
I thought I had 'got' globals but this one seems strange. I want my example function 'doIt' to use and optionally modify a module variable 'gname', so I declare 'global gname' in the function, but...
2
by: xml0x1a | last post by:
How do I use exec? Python 2.4.3 ---- from math import * G = 1 def d(): L = 1 exec "def f(x): return L + log(G) " in globals(), locals() f(1)
5
by: Steven W. Orr | last post by:
I have two seperate modules doing factory stuff which each have the similar function2: In the ds101 module, def DS101CLASS(mname,data): cname = mname+'DS101' msg_class = globals() msg =...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
2
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

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.