Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
use of global
#19
To add onto the conversation, the following two implementations effectively have no functional difference in the program; the latter does have an unstated benefit though.

def f1():
    global a, b
    a += 4
    b += 5

def f2(a, b):
    return a + 4, b + 5

a = 5
b = 4
f1()
print(a, b)

a = 5
b = 4
a, b = f2(a, b)
print(a, b)
What happens if you need to write a new program using the same logic as f1() but you want to preserve the original values of the variables? Well, you have to rewrite f1() altogether. Then, if the logic changes, you now have two versions of it to update.

With f2(), you can reset the original variables or not; that's entirely up to the caller. f2() is infinitely reusable and can be employed even without global variables existing. Plus, f2() is 100% testable because it's stateless. With the same input, it will always have the same output; whereas f1() is entirely dependent on unseen and possibly unknown values - this is what makes global variables difficult to follow.
Reply


Messages In This Thread
use of global - by wpo - Sep-30-2019, 08:53 AM
RE: use of global - by buran - Sep-30-2019, 09:00 AM
RE: use of global - by wpo - Sep-30-2019, 09:13 AM
RE: use of global - by newbieAuggie2019 - Sep-30-2019, 10:28 AM
RE: use of global - by newbieAuggie2019 - Sep-30-2019, 10:34 AM
RE: use of global - by buran - Sep-30-2019, 10:33 AM
RE: use of global - by newbieAuggie2019 - Sep-30-2019, 12:48 PM
RE: use of global - by wpo - Sep-30-2019, 10:38 AM
RE: use of global - by newbieAuggie2019 - Sep-30-2019, 10:55 AM
RE: use of global - by buran - Sep-30-2019, 10:43 AM
RE: use of global - by wpo - Sep-30-2019, 11:56 AM
RE: use of global - by buran - Sep-30-2019, 12:47 PM
RE: use of global - by wpo - Sep-30-2019, 01:27 PM
RE: use of global - by newbieAuggie2019 - Sep-30-2019, 02:14 PM
RE: use of global - by ichabod801 - Sep-30-2019, 01:43 PM
RE: use of global - by wpo - Sep-30-2019, 03:06 PM
RE: use of global - by buran - Sep-30-2019, 03:21 PM
RE: use of global - by ichabod801 - Sep-30-2019, 03:30 PM
RE: use of global - by stullis - Sep-30-2019, 07:45 PM
RE: use of global - by micseydel - Oct-02-2019, 10:06 PM
RE: use of global - by steve_shambles - Oct-17-2019, 04:21 AM
RE: use of global - by buran - Oct-17-2019, 06:13 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Global variable does not seem to be global. Columbo 6 5,327 Jul-15-2019, 11:00 PM
Last Post: Columbo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020