473,770 Members | 1,652 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

function in a function accessing vars

Hi all,

I wanted to solve a small problem, and I have a function that is
typically meant only as a function belonging inside another function.
>From the inner function I want to access a variable from the outer
function like;

def A():
some_var = 1
def B():
some_var += 1

B()
But this does not work, the function B does not recognize the
some_var. In my mind I thought the scope would propagate to the new
function and the vars would still be accessible.

How can I go about this?

With regards
- Jorgen
Jun 6 '07 #1
3 1285
Jorgen Bodde wrote:
Hi all,

I wanted to solve a small problem, and I have a function that is
typically meant only as a function belonging inside another function.
>>From the inner function I want to access a variable from the outer
function like;

def A():
some_var = 1
def B():
some_var += 1

B()
But this does not work, the function B does not recognize the
some_var. In my mind I thought the scope would propagate to the new
function and the vars would still be accessible.

How can I go about this?
The problem here is the way python determines which variables are local to a
function - by inspecting left sides.

I'm not sure if there are any fancy inspection/stackframe/cells-hacks to
accomplish what you want. But the easiest solution seems to be a
(admittedly not too beautiful)

def A():
some_var = [1]
def B(v):
v[0] += 1

B(some_var)
Or you should consider making A a callable class and thus an instance, and
some_var an instance variable. Always remember: "a closure is a poor
persons object, and an object is a poor mans closure"

Diez
Jun 6 '07 #2
Hi Diez,

Thanks, I thought it worked similar to C++ where a higher compound
could access a lower section. But as it is not straight forward, I
think it is better to embed the functionality inside a class, and make
it a member variable .. now why didn't I think of that ;-)

Thanks,
- Jorgen

On 6/6/07, Diez B. Roggisch <de***@nospam.w eb.dewrote:
Jorgen Bodde wrote:
Hi all,

I wanted to solve a small problem, and I have a function that is
typically meant only as a function belonging inside another function.
>From the inner function I want to access a variable from the outer
function like;

def A():
some_var = 1
def B():
some_var += 1

B()
But this does not work, the function B does not recognize the
some_var. In my mind I thought the scope would propagate to the new
function and the vars would still be accessible.

How can I go about this?

The problem here is the way python determines which variables are local to a
function - by inspecting left sides.

I'm not sure if there are any fancy inspection/stackframe/cells-hacks to
accomplish what you want. But the easiest solution seems to be a
(admittedly not too beautiful)

def A():
some_var = [1]
def B(v):
v[0] += 1

B(some_var)
Or you should consider making A a callable class and thus an instance, and
some_var an instance variable. Always remember: "a closure is a poor
persons object, and an object is a poor mans closure"

Diez
--
http://mail.python.org/mailman/listinfo/python-list
Jun 6 '07 #3
On Jun 6, 6:40 am, "Jorgen Bodde" <jorgen.maill.. .@gmail.comwrot e:
Hi Diez,

Thanks, I thought it worked similar to C++ where a higher compound
could access a lower section.
It can 'access a lower section'; what it can't do is *change* that
'lower section'; in your example case with an int, this matters
because ints are immutable. Lists, on the other hand, are mutable. You
can *access* the methods of the list that mutate it. You're always
working with the same list, but it has different contents when you
mutate it.
But as it is not straight forward, I
think it is better to embed the functionality inside a class, and make
it a member variable .. now why didn't I think of that ;-)
Jun 6 '07 #4

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

Similar topics

2
28034
by: André Somers | last post by:
Hi, I'm having a problem that I have a hard time understanding. I am getting a "Fatal error: Call to a member function on a non-object" on a constructor of a class, that looks like this (simplified): class phpBB_Template { var $classname = "Template"; // Root template directory.
3
8839
by: Zim | last post by:
Greetings, I have an all purpose variable dumper that uses Var_Dump to show me data structures. I have an application wide function that I simply call to dump a structure: vardump($var);
8
3973
by: ndsoumah | last post by:
hello guys I'm trying to get access to variables I put in a session variable from another page and it fails... here's the exact situation main file page1.php
0
1178
by: Uwe Mayer | last post by:
Hi, I've got a class that receives a function in the constructor and uses the __call__ method to execute the aforementioned function when the instance object is called: class foo(object): def __init__(self, func): self.func = func def __call__(self, *arg, **kwarg):
7
1464
by: vegetax | last post by:
I i need a decorator that adds a local variable in the function it decorates, probably related with nested scopes, for example: def dec(func): def wrapper(obj = None): if not obj : obj = Obj() <bind obj to func> return func() return wrapper()
5
14807
by: David Rasmussen | last post by:
If I have a string that contains the name of a function, can I call it? As in: def someFunction(): print "Hello" s = "someFunction" s() # I know this is wrong, but you get the idea... /David
0
401
by: Marty Scholes | last post by:
I may have found a bug. I have a table: CREATE TABLE onlpcd_stat ( sel BIGSERIAL PRIMARY KEY, user_id INTEGER NOT NULL REFERENCES onlpcd_user ON DELETE CASCADE, vars TEXT, /* string of Perl var hash */ cre_ts TIMESTAMP DEFAULT NOW()
11
1534
by: Ryan Krauss | last post by:
I have a set of Python classes that represent elements in a structural model for vibration modeling (sort of like FEA). Some of the parameters of the model are initially unknown and I do some system identification to determine the parameters. After I determine these unknown parameters, I would like to substitute them back into the model and save the model as a new python class. To do this, I think each element needs to be able to read...
0
1442
by: Gary Herron | last post by:
Jacob Davis wrote: Yuck, YUCK, YUCK! You are breaking *so* many good-programming-practices, I hardly know where to start. First off: A python global is not what you think. There are *no* program wide globals. There are only module wide globals. Also, the "global isglobal" is absolutely meaningless as anything declared there is a (module level) global by definition.
0
9595
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
9432
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,...
1
10008
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
8891
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
7420
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
5454
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3974
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
2
3578
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2822
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.