Do you use the "global" statement in Python? [closed]
I was reading a question about the Python global statement ( "Python scope" ) and I was remembering about how often I used this statement when I was a Python beginner (I used global a lot) and how, nowadays, years later, I don't use it at all, ever. I even consider it a bit "un-pythonic".
Do you use this statement in Python ? Has your usage of it changed with time ?
Asked by: Dainton602 | Posted: 28-01-2022
Answer 1
I use 'global' in a context such as this:
_cached_result = None
def myComputationallyExpensiveFunction():
global _cached_result
if _cached_result:
return _cached_result
# ... figure out result
_cached_result = result
return result
I use 'global' because it makes sense and is clear to the reader of the function what is happening. I also know there is this pattern, which is equivalent, but places more cognitive load on the reader:
def myComputationallyExpensiveFunction():
if myComputationallyExpensiveFunction.cache:
return myComputationallyExpensiveFunction.cache
# ... figure out result
myComputationallyExpensiveFunction.cache = result
return result
myComputationallyExpensiveFunction.cache = None
Answered by: Briony362 | Posted: 01-03-2022
Answer 2
I've never had a legit use for the statement in any production code in my 3+ years of professional use of Python and over five years as a Python hobbyist. Any state I need to change resides in classes or, if there is some "global" state, it sits in some shared structure like a global cache.
Answered by: Thomas667 | Posted: 01-03-2022Answer 3
I've used it in situations where a function creates or sets variables which will be used globally. Here are some examples:
discretes = 0
def use_discretes():
#this global statement is a message to the parser to refer
#to the globally defined identifier "discretes"
global discretes
if using_real_hardware():
discretes = 1
...
or
file1.py:
def setup():
global DISP1, DISP2, DISP3
DISP1 = grab_handle('display_1')
DISP2 = grab_handle('display_2')
DISP3 = grab_handle('display_3')
...
file2.py:
import file1
file1.setup()
#file1.DISP1 DOES NOT EXIST until after setup() is called.
file1.DISP1.resolution = 1024, 768
Answered by: Elise719 | Posted: 01-03-2022
Answer 4
In my view, as soon as you feel the need to use global variables in a python code, it's a great time to stop for a bit and work on refactoring of your code.
Putting the global
in the code and delaying the refactoring process might sound promising if your dead-line is close, but, believe me, you're not gonna go back to this and fix unless you really have to - like your code stopped working for some odd reason, you have to debug it, you encounter some of those global
variables and all they do is mess things up.
So, honestly, even it's allowed, I would as much as I can avoid using it. Even if it means a simple classes-build around your piece of code.
Answered by: Sienna672 | Posted: 01-03-2022Answer 5
Objects are the prefered way of having non-local state, so global is rarely needed. I dont think the upcoming nonlocal modifier is going to be widely used either, I think its mostly there to make lispers stop complaining :-)
Answered by: Sawyer372 | Posted: 01-03-2022Answer 6
I use it for global options with command-line scripts and 'optparse':
my main() parses the arguments and passes those to whatever function does the work of the script... but writes the supplied options to a global 'opts' dictionary.
Shell script options often tweak 'leaf' behavior, and it's inconvenient (and unnecessary) to thread the 'opts' dictionary through every argument list.
Answered by: John776 | Posted: 01-03-2022Answer 7
I avoid it and we even have a pylint rule that forbids it in our production code. I actually believe it shouldn't even exist at all.
Answered by: Elise623 | Posted: 01-03-2022Answer 8
Rarely. I've yet to find a use for it at all.
Answered by: Kellan701 | Posted: 01-03-2022Answer 9
It can be useful in threads for sharing state (with locking mechanisms around it).
However, I rarely if ever use it.
Answered by: Adrian569 | Posted: 01-03-2022Answer 10
I've used it in quick & dirty, single-use scripts to automate some one-time task. Anything bigger than that, or that needs to be reused, and I'll find a more elegant way.
Answered by: Kevin763 | Posted: 01-03-2022Answer 11
Once or twice. But it was always good starting point to refactor.
Answered by: Walter581 | Posted: 01-03-2022Answer 12
If I can avoid it, no. And, to my knowledge, there is always a way to avoid it. But I'm not stating that it's totally useless either
Answered by: Joyce102 | Posted: 01-03-2022Similar questions
Using "with" statement for CSV files in Python
Is it possible to use the with statement directly with CSV files? It seems natural to be able to do something like this:
import csv
with csv.reader(open("myfile.csv")) as reader:
# do things with reader
But csv.reader doesn't provide the __enter__ and __exit__ methods, so this doesn't work. I can however do it in two steps:
import ...
python - pysqlite user types in select statement
Using pysqlite how can a user-defined-type be used as a value in a comparison, e. g: “... WHERE columnName > userType”?
For example, I've defined a bool type with the requisite registration, converter, etc. Pysqlite/Sqlite responds as expected for INSERT and SELECT operations (bool 'True' stored as an integer 1 and returned as True).
But it fails when the bool is used in either “SELECT * from tasks WHERE di...
python - import statement fails for one module
Ok I found the problem, it was an environmental issue, I had the same modules (minus options.py) on the sys.path and it was importing from there instead. Thanks everyone for your help.
I have a series of import statements, the last of which will not work. Any idea why? options.py is sitting in the same directory as everything else.
from snipplets.main import MainHandler
from snipplets.createnew imp...
python - Dividing in an if statement
In Python, if I had a range, and I wanted to iterate over it and divide each number by another number, could I do that in a if statement.
a = range(20)
for i in a:
if i / 3 == True:
print i
Disable Python return statement from printing object it returns
I want to disable "return" from printing any object it is returning to python shell.
e.g A sample python script test.py looks like:
def func1():
list = [1,2,3,4,5]
print list
return list
Now, If i do following:
python -i test.py
>>>func1()
This always give me two prints on python shell.
I just want to print and get returned ob...
python - for statement and i.find in list
for a in ('90','52.6', '26.5'):
if a == '90':
z = (' 0',)
elif a == '52.6':
z = ('0', '5')
else:
z = ('25')
for b in z:
cmd = exepath + ' -a ' + str(a) + ' -b ' + str(b)
process = Popen(cmd, shell=True, stderr=STDOUT, stdout=PIPE)
outputstring = process.communicate()[0]
outputlist = outputstring.splitlines()
for i in outputlist:
...
python - print statement in for loop only executes once
I am teaching myself python. I was thinking of small programs, and came up with an idea to do a keno number generator. For any who don't know, you can pick 4-12 numbers, ranged 1-80, to match. So the first is part asks how many numbers, the second generates them. I came up with
x = raw_input('How many numbers do you want to play?')
for i in x:
random.randrange(1,81)
print i
Which doesn'...
Python and if statement
I'm running a script to feed an exe file a statement like below:
for j in ('90.','52.62263.','26.5651.','10.8123.'):
if j == '90.':
z = ('0.')
elif j == '52.62263.':
z = ('0.', '72.', '144.', '216.', '288.')
elif j == '26.5651':
z = ('324.', '36.', '108.', '180.', '252.')
else:
z = ('288.', '0.', '72.', '144.', '216.')
for k in z:
exepath = os.pa...
python - Why print statement is not pythonic?
Closed. This question is opinion-based. It is not c...
closures - Python nonlocal statement / keyword
What does nonlocal do in Python 3.x?
To close debugging questions where OP needs nonlocal and doesn't realize it, please use Is it possible to modify variable in python that is in outer, but not global, scope? instead.
Although Python 2 is
Still can't find your answer? Check out these communities...
PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python