3 ms·
Can you give an example of a truly global variable? I do try to avoid those. If we’re talking about global parameters, I usually put those in all-caps near the
by DATACOMMANDER 8y ago
Can you give an example of a truly global variable? I do try to avoid those. If we’re talking about global parameters, I usually put those in all-caps near the beginning of whatever module has to use them, and have them default to values that live in a top-level text file that the user can edit between invocations. But for global(ish) variables I do use classes, so other parts of the code can instantiate objects that are responsible for their values and call methods on those objects rather than mutate global state arbitrarily. I hope I’m not writing spaghetti code by doing this. The objects that manage these variables definitely never pass them to other objects (which in my mind would defeat the purpose). For example, if I need to use an external RESTful API, then things like token expiration are unavoidable state that must be dealt with, but I’ll write a paper-thin wrapper around a Requests session that shields consumers of the API from that sort of bookkeeping. If Python had private members I’d use them, but I at least use the “_” prefix to signal to clients that if they’re accessing the member directly they should stop and think about what they’re trying to accomplish.
It sounds like maybe you’re talking about what I’ve heard referred to as “cross-cutting concerns” that happen to be stateful. I haven’t developed anything large or complex enough to run into that, but I can imagine (in a fuzzy sort of way) code that contorts itself to avoid globals when a far simpler solution would be, “Use this small number of globals, but be careful.”
I could be way off here. I’m eager to hear your response.