Will on 3 Sep 2018 14:11:48 -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
> files.
>
> 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:
https://stackoverflow.com/questions/15959534/python-visibility-of-global-variables-in-imported-modules/15959638
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 ~{:-)
pj@illuminatedcomputing.com
___________________________________________________________________________
Philadelphia Linux Users Group -- http://www.phillylinux.org
Announcements - http://lists.phillylinux.org/mailman/listinfo/plug-announce
General Discussion -- http://lists.phillylinux.org/mailman/listinfo/plug
___________________________________________________________________________ Philadelphia Linux Users Group -- http://www.phillylinux.org Announcements - http://lists.phillylinux.org/mailman/listinfo/plug-announce General Discussion -- http://lists.phillylinux.org/mailman/listinfo/plug