473,395 Members | 2,443 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 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 1277
"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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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...
0
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,...

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.