Functions access to global variables - python

I am working on a text-based game to get more practice in Python. I turned my 'setup' part of the game into a function so I could minimize that function and to get rid of clutter, and so I could call it if I ever wanted to change some of the setup variables.
But when I put it all into a function, I realized that the function can't change global variables unless you do all of this extra stuff to let python know you are dealing with the global variable, and not some individual function variable.
The thing is, a function is the only way I know of to re-use your code, and that is all I really need, I do not need to use any parameters or anything special. So is there anything similar to functions that will allow me to re-use code, and will not make me almost double the length of my code to let it know it's a global variable?

You can list several variables using the same global statement.
An example:
x = 34
y = 32
def f():
global x,y
x = 1
y = 2
This way your list of global variables used within your function will can be contained in few lines.
Nevertheless, as #BrenBarn has stated in the comments above, if your function does little more than initializating variables, there is no need to use a function.

Take a look at this.
Using a global variable inside a function is just as easy as adding global to the variable you want to use.

Related

Conditionally declare variables as global inside a Python function

I am developing a Python function of which the intermediate results should conditionally be accessible outside of the function, for plotting. It concerns > 20 variables of large size. To preserve memory I aim to only make the variables globally available in case the plotting is needed.
See the following code snippet I initially expected to work like desired:
def x():
if True:
global a
a = 10
return
x()
print(a)
Expected result: variable 'a' can be printed only if the if statement is executed.
Actual result: variable 'a' can always be printed.
I tried many things but cannot seem to achieve the desired behaviour. Proper programming would be to return the variables needed to the global scope, using 'return'. However, I do not know how to do that conditionally in a pretty way, with this many variables. Can anybody explain the behaviour I see, and suggest how to achieve the desired behaviour?
The determination of whether a variable is local or global is made when the function is being compiled, not when it runs. So this can't be dynamic.
You can solve it by using the locals() and globals() functions to access the different variable environments.
def x():
env = locals()
if <condition>:
env = globals()
env['a'] = 10
return
x()
print(a)

"Global variable" in multiple functions

I am trying to collect data with a global variable, without returning the variable
def collect_result(result):
is_global = "Res_collected" in globals()
if is_global == False:
global Res_collected
Res_collected = []
elif is_global == True:
Res_collected.append(result)
return
How can I use or call this variable in another function?
You don't need to do anything special in order to read the value of a global variable inside another function, you can just refer to it by name, so print(Res_collected), for example.
If you want to write to the global variable, you would do that in the same way you're already doing it in your collect_result function, by using the global keyword. This is a decent introductory tutorial.
As others have already pointed out, it's generally not a good idea to use global variables. A better alternative is to pass your collection of results as a parameter to whatever functions are going to use them. That way it is clear and explicit what data is being read or modified by each function.
Global variables can hide important clues about what data is being used, where and how, which makes the code harder to understand, and can lead to other problems further down the line.
This is a really bad idea to use globals as indicated by #quamrana and #deceze but if you want to try (not for production please), I suppose the code below should work:
>>> globals().setdefault('Res_collected', []).append(res)

Accessing variable inside a function from external file?

I have a file
outSimulation.py this file has a function called
outlet1 and inside this function there is a variable called data
I want to access this data variable from another program called main.py
I have tried it with absolute imports
from outSimulation import outlet1
values = outlet1.data()
but it doesnt work. Any help is appreciated.
You cannot* access a variable which is local to a function from outside the function.
If you want to access the value of data from a function which is called by outlet1(), you should pass data to that function.
If you want to access the value of data after outlet1() finishes running, you should return data (possibly along with other things) from outlet1().
Alternatively, you can make data a module-level variable. Assuming you assign something to data within outlet1(), you would make it a module-level variable using the global keyword,
def outlet1():
global data
# code
data = ...
# more code
but this tends to be less clean than the other methods.
There are other solutions if outlet1() is defined within a class, but your question suggests that's not the case so I won't get into that.
*Well... uh, never mind. There are some wacky things you can do for debugging, but you're better off not considering those for your purposes.
Functions are not classes, and are specifically designed so that you CAN'T do what you're trying to do. That's the whole basis of functional programming and the concepts behind encapsulation. Even if your function was a class, your code still wouldn't work because you're trying to call the variable as a function (by adding () to data).
Either create data as a global variable that can be referenced inside the function or have the function return a tuple with multiple items, including the original return value and the data variable (messy). You could also rewrite the function in an object-oriented way if that approach suits your problem domain, in which case your code above would make more sense.

How do I make a variable created inside a function become global?

I have a function in a program that I`m working at and I named a variable inside this function and I wanted to make it global. For example:
def test():
a = 1
return a
test()
print (a)
And I just can`t access "a" because it keeps saying that a is not defined.
Any help would be great, thanks.
I have made some changes in your function.
def test():
# Here I'm making a variable as Global
global a
a = 1
return a
Now if you do
print (a)
it outputs
1
As Vaibhav Mule answered, you can create a global variable inside a function but the question is why would you?
First of all, you should be careful with using any kind of global variable, as it might be considered as a bad practice for this. Creating a global from a function is even worse. It will make the code extremely unreadable and hard to understand. Imagine, you are reading the code where some random a is used. You first have to find where that thing was created, and then try to find out what happens to it during the program execution. If the code is not small, you will be doomed.
So the answer is to your question is simply use global a before assignment but you shouldn't.
BTW, If you want c++'s static variable like feature, check this question out.
First, it is important to ask 'why' would one want that? Essentially what a function returns is a 'local computation' (normally). Having said so - if I have to use return 'value' of a function in a 'global scope', it's simply easier to 'assign it to a global variable. For example in your case
def test():
a = 1 # valid this 'a' is local
return a
a = test() # valid this 'a' is global
print(a)
Still, it's important to ask 'why' would I want to do that, normally?

Using the same name for variables which are in different functions?

I've been searching a while for my question but haven't found anything of use. My question is rather easy and straightforward.
Is it preferable or perhaps "pythonic" to use the same name for a certain variable which will appear in different functions, but with the same purpose?
For example:
def first_function():
pt = win.getMouse() # This waits for a mouseclick in a graphical window.
if blabla.button.clicked(pt):
second_function()
def second_function():
pt = win.getMouse()
if whatever.button.clicked(pt):
third_function()
Does it matter if the variable reference (pt) to win.getMouse() in the second_function() has the same name as the variable in the first_function()? Or should the variable pt in the second function be named something else?
Names in functions are local; reuse them as you see fit!
In other words, the names in one function have no relationship to names in another function. Use good, readable variable names and don't worry about names clashing.
Its not about "Pythonic" or not. In programming you always wish your variables to have a meaning, if the same name occures in differend functions that means they do things with the same purpose or same params. Its fine to use same names in different functions, as long as they don't collide and make problems
Variables defined in a function have Function Scope and are only visible in the body of the function.
See: http://en.wikipedia.org/wiki/Scope_(computer_science)#Python for an explanation of Python's scoping rules.

Categories