Accessing a Variable Defined in a Parent Function

Can functions access variables defined in its own parent function?

The reason why the first example fails and the second 'works' has to do with scope and closure. You can think of a function's 'curly braces' as the enclosure around its scope - or sphere of influence.

The first example fails because myBigFunction()'s variable is not accessible to subFunction1()'s scope. myBigFunction() also doesn't wrap subFunction1() which would provide a closure. Check out closures here.

However, add() is declared within the scope of the getScore() function. getScore() 'wraps' add() - providing a closure so that add() has access to variables within getScore()'s scope.

Access a variable by name defined in a parent function from a nested function

Yes it's possible, but you are working against Python, don't do this:

In [1]: import inspect

In [2]: def f():
...: x = 1
...: def g():
...: print(inspect.currentframe().f_back.f_locals['x'])
...: g()
...:

In [3]: f()
1

Seriously, don't. Write good code, not bad code. For all of us.

Accessing a variable defined in a parent function

PHP<5.3 does not support closures, so you'd have to either pass $foo to inner() or make $foo global from within both outer() and inner() (BAD).

In PHP 5.3, you can do

function outer()
{
$foo = "...";
$inner = function() use ($foo)
{
print $foo;
};
$inner();
}
outer();
outer();

Accessing variables passed to, or defined in, parent R function

The issue is that Foo is defined in the global environment.

Adding the line

  environment(Foo) <- environment()

before calling Foo within Func1 and Func2 produced the desired behaviour.

How to access variable from the parent function in R

you can access the scope of the calling function through the called function's parent frame:

mother <- function(){
year_change = 8
child()
}

child <- function(){
print(parent.frame()$year_change)
}

... or define them in one of the function's immediate parent environments:

mother <- function(){ ## now the immediate parent environment
year_change = 8
child <- function(){
print(year_change)
}
child()
}

... or in the global environment:

year_change = 8 ## the global environment

mother <- function(){
print(paste("mom's idea of year_change is:", year_change))
child <- function(){
print(paste("kid's idea of year_change is:", year_change))
}
child()
}

Note that the immediate parent environment outmatches the farther ancestors if variables have the same name.

Details of scoping e.g. in H. Wickham: Advanced R


Edit

Shamefully forgot the possibility to pass variables through by taking advantage of the ellipsis ... argument.

example

mother_says <- function(...){
tell_child(...)
}

tell_child <- function(...){
args <- list(...)
print(paste("Mom says:", args$message_to_daughter))
tell_grandchild(...)
}

tell_grandchild <- function(...){
args <- list(...)
print(paste("Granny says:", args$message_to_grandchild))
}

example's output:

## > mother_says(message_to_daughter = "Hi, daughter, how're you?",
## + message_to_grandchild = "Grandchild, sweetie!"
## + )
##
## [1] "Mom says: Hi, daughter, how're you?"
## [1] "Granny says: Grandchild, sweetie!"

Accessing parent function's variable in a child function called in the parent using python

In this case, you'd probably like to use a class. They are really easy to get your head around. Note the self variable that is passed, and take a look here for a quick explanation of scope in classes.

#!/usr/bin/env python3

class Family(object):

def parent(self):
self.test = 0
self.child()

def child(self):
self.test += 1
print(self.test)

if __name__ == "__main__":
Family().parent()

So, to translate to your code:

#!/usr/bin/env python3

class Graph(object):
def depthFirstSearch(self):
for vertex in self.adjacency_list:
vertex.status = "not visited"
vertex.previous = None

self.visit_count = 0
for vertex in self.adjacency_list:
if vertex.status == "not visited":
self.depthFirstSearchVisit(vertex)

def depthFirstSearchVisit(self, vertex):
self.visit_count += 1

vertex.distance = self.visit_count
vertex.status = "waiting"

for edge in vertex.edges:
if edge.status == "not visited":
edge.previous = vertex
self.depthFirstSearchVisit(edge)

vertex.status = "visited"
self.visit_count += 1
vertex.distance_finished = self.visit_count

class Edge(object):
status = "not vistited"

class Vertex(object):
def __init__(self):
self.edges = [Edge(), Edge()]

if __name__ == "__main__":
graph = Graph()
graph.adjacency_list = [Vertex(), Vertex()]
graph.depthFirstSearch()

Nothing fancy needed.



Related Topics



Leave a reply



Submit