Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you use the "global" statement in Python? [closed]

Tags:

python

global

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 ?

like image 817
Aurelio Martin Massoni Avatar asked Sep 28 '08 19:09

Aurelio Martin Massoni


People also ask

When global is used in Python?

In Python, global keyword allows you to modify the variable outside of the current scope. It is used to create a global variable and make changes to the variable in a local context.

Is it good to use global in Python?

While in many or most other programming languages variables are treated as global if not declared otherwise, Python deals with variables the other way around. They are local, if not otherwise declared. The driving reason behind this approach is that global variables are generally bad practice and should be avoided.

What are two reasons why you should not use global variables in Python?

The reason global variables are bad is that they enable functions to have hidden (non-obvious, surprising, hard to detect, hard to diagnose) side effects, leading to an increase in complexity, potentially leading to Spaghetti code.

Do you need to declare global variable in Python?

To create a global variable in Python, you need to declare the variable outside the function or in a global scope.


1 Answers

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 
like image 60
Jerub Avatar answered Sep 19 '22 13:09

Jerub