How to Access Function Variables in Another Function

Calling variable defined inside one function from another function

One approach would be to make oneFunction return the word so that you can use oneFunction instead of word in anotherFunction :

def oneFunction(lists):
category = random.choice(list(lists.keys()))
return random.choice(lists[category])


def anotherFunction():
for letter in oneFunction(lists):
print("_", end=" ")

Another approach is making anotherFunction accept word as a parameter which you can pass from the result of calling oneFunction:

def anotherFunction(words):
for letter in words:
print("_", end=" ")
anotherFunction(oneFunction(lists))

And finally, you could define both of your functions in a class, and make word a member:

class Spam:
def oneFunction(self, lists):
category=random.choice(list(lists.keys()))
self.word=random.choice(lists[category])

def anotherFunction(self):
for letter in self.word:
print("_", end=" ")

Once you make a class, you have to instantiate an instance and access the member functions:

s = Spam()
s.oneFunction(lists)
s.anotherFunction()

Accessing variables from other functions without using global variables

To make a variable calculated in function A visible in function B, you have three choices:

  • make it a global,
  • make it an object property, or
  • pass it as a parameter when calling B from A.

If your program is fairly small then globals are not so bad. Otherwise I would consider using the third method:

function A()
{
var rand_num = calculate_random_number();
B(rand_num);
}

function B(r)
{
use_rand_num(r);
}

How to access a variable in one python function in another function

You have to declare the variable to be global, then use it. Like so:

def add_to_outside():
global outside #say that it is global
outside = 1 #now create it!

def see_it():
global outside #say that it is global
print(outside)

##As shown:
add_to_outside()
see_it()
#output: 1

The keyword global at the start makes all variables of that name in the function reference the global values. You don't say a variable is global and change it in the same statement.

Also, only put the global keyword at the start of the function. It doesn’t need to be next to the changes to the variables, and is only needed once.

To declare multiple variables global, do it like this:

global var1, var2, var3 #etc.

How to Access Function variables in Another Function

Return them from your first function and accept them in your second function. Example -

def xxx():
a=10
b=15
c=20
return a,b

def yyy():
a,b = xxx()
print a ### value a from xxx()
print b ### value b from xxx()

yyy()

Access variable from a different function from another file

You can access the value of a variable in a function by 1) returning the value in the function, 2) use a global variable in the module, or 3) define a class.

If only want to access a single variable local to a function then the function should return that value. A benefit of the class definition is that you may define as many variables as you need to access.

1. Return value

def champs_info(champname:str, tier_str:int):  
...
tier = tier_access.text
return tier

2. global

tier = None
def champs_info(champname:str, tier_str:int):
global tier
...
tier = tier_access.text

Global tier vairable is accessed.

from mypythonlib import myfunctions

def test_champs_info():
myfunctions.champs_info("abomination", 6)
return myfunctions.tier

print(test_champs_info())

3. class definition:

class Champ:
def __init__(self):
self.tier = None
def champs_info(self, champname:str, tier_str:int):
...
self.tier = tier_access.text

test_functions.py can call champs_info() in this manner.

from mypythonlib import myfunctions

def test_champs_info():
info = myfunctions.Champ()
info.champs_info("abomination", 6)
return info.tier

print(test_champs_info())

Accessing variables in a function within a function

I do encourage you to read about lexical scoping,
but I think a good approach to avoid writing a lot of variables could be:

get_args_for <- function(fun, env = parent.frame(), inherits = FALSE, ..., dots) {
potential <- names(formals(fun))

if ("..." %in% potential) {
if (missing(dots)) {
# return everything from parent frame
return(as.list(env))
}
else if (!is.list(dots)) {
stop("If provided, 'dots' should be a list.")
}

potential <- setdiff(potential, "...")
}

# get all formal arguments that can be found in parent frame
args <- mget(potential, env, ..., ifnotfound = list(NULL), inherits = inherits)
# remove not found
args <- args[sapply(args, Negate(is.null))]
# return found args and dots
c(args, dots)
}

f_a <- function(b, c = 0, ..., d = 1) {
b <- b + 1
c(b = b, c = c, d = d, ...)
}

f_e <- function() {
b <- 2
c <- 2
arg_list <- get_args_for(f_a, dots = list(5))
do.call(f_a, arg_list)
}

> f_e()
b c d
3 2 1 5

Setting inherits = FALSE by default ensures that we only get variables from the specified environment.
We could also set dots = NULL when calling get_args_for so that we don't pass all variables,
but leave the ellipsis empty.

Nevertheless, it isn't entirely robust,
because dots is simply appended at the end,
and if some arguments are not named,
they could end up matched by position.
Also, if some values should be NULL in the call,
it wouldn't be easy to detect it.


I would strongly advise against using these below inside an R package.
Not only will it be rather ugly,
you'll get a bunch of notes from R's CMD check regarding undefined global variables.

Other options.

f_a <- function() {
return(b + c)
}

f_e <- function() {
b <- 2
c <- 2
# replace f_a's enclosing environment with the current evaluation's environment
environment(f_a) <- environment()
d <- f_a()
d
}

> f_e()
[1] 4

Something like the above probably wouldn't work inside an R package,
since I think a package's functions have their enclosing environments locked.

Or:

f_a <- function() {
with(parent.frame(), {
b + c
})
}

f_e <- function() {
b <- 2
c <- 2
f_a()
}

> f_e()
[1] 4

That way you don't modify the other function's enclosing environment permanently.
However, both functions will share an environment,
so something like this could happen:

f_a <- function() {
with(parent.frame(), {
b <- b + 1
b + c
})
}

f_e <- function() {
b <- 2
c <- 2
d <- f_a()
c(b,d)
}

> f_e()
[1] 3 5

Where calling the inner function modifies the values in the outer environment.

Yet another option that is a bit more flexible,
since it only modifies the enclosing environment temporarily by using eval.
However, there are certain R functions that detect their current execution environment through "daRk magic",
and cannot be fooled by eval;
see this discussion.

f_a <- function() {
b <- b + 1
b + c
}

f_e <- function() {
b <- 2
c <- 2
# use current environment as enclosing environment for f_a's evaluation
d <- eval(body(f_a), list(), enclos=environment())
c(b=b, d=d)
}

> f_e()
b d
2 5

Access variable from function to another function

In object oriented programming, different methods (functions) of an object can share common variables using the 'this' keyword. Here in this example I declare a class called 'Context' with two methods 'nameOutside' and 'nameInside'. Then I instantiate an object from the class, storing the reference in the 'context' variable. Finally I call the nameInside() method of that object.

class Context {
nameOutside() {
console.log(this.name);
}

nameInside() {
this.name = "my name";
this.nameOutside();
}
}

let context = new Context();
context.nameInside();

How to access variables defined and declared in one function in another function?

The C++ way is to pass abc by reference to your function:

void function1()
{
std::string abc;
function2(abc);
}
void function2(std::string &passed)
{
passed = "new string";
}

You may also pass your string as a pointer and dereference it in function2. This is more the C-style way of doing things and is not as safe (e.g. a NULL pointer could be passed in, and without good error checking it will cause undefined behavior or crashes.

void function1()
{
std::string abc;
function2(&abc);
}
void function2(std::string *passed)
{
*passed = "new string";
}


Related Topics



Leave a reply



Submit