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.

2
  • 6
    Did you try searching? Searching for "python local global performance" turned up this Stack Overflow question as the first result. More importantly, mutable global variables are a bad idea.
    – Doval
    Commented Feb 3, 2015 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.
    – user53141
    Commented Feb 4, 2015 at 4:25

1 Answer 1

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.

1
  • 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
    Commented Dec 23, 2020 at 11:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.