[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

How should we use global variables correctly?

On 8/22/19 10:00 AM, Windson Yang wrote:
> I can 'feel' that global variables are evil. I also read lots of articles
> proves that (http://wiki.c2.com/?GlobalVariablesAreBad). However, I found
> CPython Lib use quite a lot of `global` keyword. So how should we use
> `global` keyword correctly? IIUC, it's fine that we use `global` keyword
> inside the Lib since most of the time the user just import the lib and call
> the API. In any other situation, we should avoid using it. Am I right?

The "global" keyword only refers to the current module as far as I know.
 Thus global variables are global only to the current python file, so
the damage, as it were, is limited in scope.  And it's only required if
you plan to write to a global variable from another scope; you can
always read from a parent scope if the name hasn't been used by the
local scope.  I'm sure there are use cases for using the global keyword.
 It's not evil.  It's just not necessary most of the time.  I don't
think I've ever used the "global" keyword.  If I need to share state, or
simple configuration information, between modules, I place those
variables in their own module file and import them where I need them.