2

Hey so i was wondering which is the more efficient way, or better practice to do in this situation.

1,

def function():
    global number
    number += 2

Or 2,

def function(number):
    return number += 2

Thanks.

John Ellis
  • 31
  • 1
  • 1
  • 2
  • 6
    Did you try searching? Searching for "python local global performance" turned up [this Stack Overflow question](http://stackoverflow.com/questions/12590058/python-performance-with-global-variables-vs-local) as the first result. More importantly, mutable global variables are a bad idea. – Doval Feb 03 '15 at 17:04
  • If you are working on something where the performance difference between a global and a local matters, you should probably not be using python in the first place. This is a micro-optimization at best, and python's reasons for existence don't include speed. – Gort the Robot Feb 04 '15 at 04:25

1 Answers1

4

Performance is irrelevant. Globals are evil (as gnat mentioned); you are best off forgetting the global keyword exists. There is always a better way.

msw
  • 1,857
  • 10
  • 16
  • 2
    Feels a bit extreme to say "performance is irrelevant"... also you mention there is a better way, but you don't mention or point to it, so it is not a very useful answer IMHO. – RogerS Dec 23 '20 at 11:00