Paul Jungwirth on 3 Sep 2018 12:31:02 -0700

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

Re: [PLUG] Off Topic: Python3 Global Variable in Separate Function File Question

On 09/03/2018 08:05 AM, Casey Bralla wrote:
Sorry for the off-topic, but I'm running Python3 on Linux :)

I'm confused by global variables in functions that are kept in separate

I understand that in Python3 variables are "inherited" into functions,
and that to make them global, they have to be declared as global within
the function.  However, if I put all my functions in a separate file and
import them, the variables that should be global are NOT global.

This StackOverflow answer should help you out:

The key line is:

> Globals in Python are global to a module, not across all modules.

You can make your script work with two changes:

1. In the imported module, make sure your variable is defined at the top-level as soon as the file is imported, whether you ever call the function or not:

    Parameter3 = 0
    def testglobal(Parameter1, Parameter2):

2. In the test script, do `import globalmodules`, not (or in addition to) `from globalmodules import *`. Then refer to `globalmodules.Parameter3`.

Paul              ~{:-)
Philadelphia Linux Users Group         --
Announcements -
General Discussion  --