Casey Bralla on 3 Sep 2018 08:05:41 -0700


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

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


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.

Here is an example that works exactly as one would expect.


# Function Test Global Functions
#
def testglobal(Parameter1, Parameter2):
    #
    #
    global  Parameter3
    #
    Parameter3 = Parameter1 + Parameter2
    print (Parameter3)
    #
    return()

Parameter1 = 10
Parameter2 = 20
Parameter3 = 0

testglobal(Parameter1, Parameter2)

print (Parameter3)


When run, this prints:
30
30
 as expected.





However, if I put the function in a separate file called
"globalmodules.py" and add an import statement, it does not work.

globalmodules.py:
def testglobal(Parameter1, Parameter2):
    #
    #
    global  Parameter3
    #
    Parameter3 = Parameter1 + Parameter2
    print (Parameter3)
    #
    return()



test.py:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
from globalmodules import *

Parameter1 = 10
Parameter2 = 20
Parameter3 = 0

testglobal(Parameter1, Parameter2)

print (Parameter3)


The printout for this program is:
30
0


Can anyone explain this to me?

I want to put all my "utility" functions in a separate file which is
available to multiple python programs.  How can I make some of these
variables global?  BTW, I realize I could make the function simply
return the variable, but my program is dealing with a  block of 55
database variables, and global variables seems the best approach for
this application.

TIA!

Attachment: pEpkey.asc
Description: application/pgp-keys

___________________________________________________________________________
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