Access a function variable outside the function without using global
You could do something along these lines (which worked in both Python v2.7.17 and v3.8.1 when I tested it/them):
def hi():
# other code...
hi.bye = 42 # Create function attribute.
sigh = 10
hi()
print(hi.bye) # -> 42
Functions are objects in Python and can have arbitrary attributes assigned to them.
If you're going to be doing this kind of thing often, you could implement something more generic by creating a function decorator that adds a this
argument to each call to the decorated function.
This additional argument will give functions a way to reference themselves without needing to explicitly embed (hardcode) their name into the rest of the definition and is similar to the instance argument that class methods automatically receive as their first argument which is usually named self
— I picked something different to avoid confusion, but like the self
argument, it can be named whatever you wish.
Here's an example of that approach:
def add_this_arg(func):
def wrapped(*args, **kwargs):
return func(wrapped, *args, **kwargs)
return wrapped
@add_this_arg
def hi(this, that):
# other code...
this.bye = 2 * that # Create function attribute.
sigh = 10
hi(21)
print(hi.bye) # -> 42
Note
This doesn't work for class methods. Just use the instance argument, named self
by convention, that's already passed to methods instead of the method's name. You can reference class-level attributes through type(self)
. See Function's attributes when in a class.
Accessing variables outside method call on an object without making them global (is it possible?)
Myself, I'd keep them in one place, without polluting the scope:
MyObject.prototype.template = function(){
this.params = {all: '', these: '', variables: '', etc: ''}
for (var i=0; i<10; i++){
callback();
}};
MyObject.prototype.myFirstMethod = function(){
var self = this;
this.template(function(){
console.log(self.params);
});
};
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())
Python - Change variable outside function without return
Here's a simple (python 2.x) example of how to 1 not use globals and 2 use a (simplistic) domain model class.
The point is: you should first design your domain model independently from your user interface, then write the user interface code calling on your domain model. In this case your UI is a Tkinter GUI, but the same domain model should be able to work with a command line UI, a web UI or whatever.
NB : for python 3.x, replace Tkinter
with tkinter
(lowercase) and you can get rid of the object
base class for Model
.
import random
from Tkinter import *
class Model(object):
def __init__(self):
self.currentMovie = 0
def UpdateCurrentMovie(self):
self.currentMovie = random.randint(0, 100)
print(self.currentMovie)
def UpdateWatched(self):
print(self.currentMovie)
def ExampleWithArgs(self, arg):
print("ExampleWithArg({})".format(arg))
def main():
model = Model()
root = Tk()
root.title("MovieSelector9000")
root.geometry("900x600")
app = Frame(root)
app.grid()
canvas = Canvas(app, width = 300, height = 75)
canvas.pack(side = "left")
button1 = Button(canvas, text = "SetRandomMovie", command=model.UpdateCurrentMovie)
button2 = Button(canvas, text = "GetRandomMovie", command=model.UpdateWatched)
button3 = Button(canvas, text = "ExampleWithArg", command=lambda: model.ExampleWithArgs("foo"))
button1.pack(anchor = NW, side = "left")
button2.pack(anchor = NW, side = "left")
button3.pack(anchor = NW, side = "left")
root.mainloop()
if __name__ == "__main__":
main()
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.
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);
}
Related Topics
How to Pass Variables Across Functions
What Does the 'U' Symbol Mean in Front of String Values
Fast Haversine Approximation (Python/Pandas)
How to Bind Self Events in Tkinter Text Widget After It Will Binded by Text Widget
How to Get Variable Data from a Class
Nested Arguments Not Compiling
How to Lowercase a String in Python
Directory-Tree Listing in Python
How to Use Stringio in Python3
Perform Commands Over Ssh with Python
Execute Code When Django Starts Once Only
How to Use Xpath with Beautifulsoup
How to Add a Constant Column in a Spark Dataframe
Convert a Number Range to Another Range, Maintaining Ratio