When to declare variables as global


28 posts   Page 2 of 2   1, 2
by BlackJack » Fri Nov 02, 2012 1:07 pm
@Grumpy Mike: In an object oriented programming language classes are the preferred language construct to describe stateful objects. That does not make it a poor language.
Code: Select all
while not self.asleep():
    sheep += 1
Posts: 288
Joined: Sat Aug 04, 2012 8:28 am
by Wisar » Sun Nov 04, 2012 2:52 pm
Python's handling of static variables is a little different than I expected but if you think of static variables being attributes to the function it makes sense. On the topic of global variables...I am completely abusing the whole dictionary concept! I have glob of context that I make available to various classes that drive my project. I define it up top and then pass it to the sub modules when I instantiate them. I know it is horridly ugly but I am going to plead the fifth and go with the quote from above..."You're writing for your own pleasure"!
Posts: 57
Joined: Tue Sep 25, 2012 6:33 am
Location: Temple near Marlow, England
by rurwin » Sun Nov 04, 2012 3:15 pm
The rule is, if the object is a true singleton, then make it global, but be aware that things that are singletons in the first incarnation of a program, may not be at a later time. On the other hand passing loads of parameters to every function is even worse for maintainability than having global variables.

As for multiple return values, they are as easy as this:
Code: Select all
def poly(x):
    return x, x*x, x*x*x

x,x2,x3 = poly(4)
print x, x2, x3

4 16 64


As for making it a class and passing that, all you are doing is making loads of global variables. If the constituent parts of the class do not belong together then the future will bring pain. For example you could have a class containing the window ID, the thread ID and the internationalisation language, and you can pass that class to every function. Then when you decide to have two threads you have to pull the thread ID out of the class, pass that every time to all functions and change every reference to it to not use the class. That's even more painful than if it was a global variable by itself. Or you clone the entire class and risk the copies getting out of sync.
User avatar
Moderator
Moderator
Posts: 2890
Joined: Mon Jan 09, 2012 3:16 pm