[python] How to make a local variable (inside a function) global

Possible Duplicate:
Using global variables in a function other than the one that created them

I'm using functions so that my program won't be a mess but I don't know how to make a local variable into global.

This question is related to python function global-variables local

The answer is


You could use module scope. Say you have a module called utils:

f_value = 'foo'

def f():
    return f_value

f_value is a module attribute that can be modified by any other module that imports it. As modules are singletons, any change to utils from one module will be accessible to all other modules that have it imported:

>> import utils
>> utils.f()
'foo'
>> utils.f_value = 'bar'
>> utils.f()
'bar'

Note that you can import the function by name:

>> import utils
>> from utils import f
>> utils.f_value = 'bar'
>> f()
'bar'

But not the attribute:

>> from utils import f, f_value
>> f_value = 'bar'
>> f()
'foo'

This is because you're labeling the object referenced by the module attribute as f_value in the local scope, but then rebinding it to the string bar, while the function f is still referring to the module attribute.


Simply declare your variable outside any function:

globalValue = 1

def f(x):
    print(globalValue + x)

If you need to assign to the global from within the function, use the global statement:

def f(x):
    global globalValue
    print(globalValue + x)
    globalValue += 1

If you need access to the internal states of a function, you're possibly better off using a class. You can make a class instance behave like a function by making it a callable, which is done by defining __call__:

class StatefulFunction( object ):
    def __init__( self ):
        self.public_value = 'foo'

    def __call__( self ):
        return self.public_value


>> f = StatefulFunction()
>> f()
`foo`
>> f.public_value = 'bar'
>> f()
`bar`

Using globals will also make your program a mess - I suggest you try very hard to avoid them. That said, "global" is a keyword in python, so you can designate a particular variable as a global, like so:

def foo():
    global bar
    bar = 32

I should mention that it is extremely rare for the 'global' keyword to be used, so I seriously suggest rethinking your design.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to global-variables

What is the best way to declare global variable in Vue.js? How do I turn off the mysql password validation? How to declare Global Variables in Excel VBA to be visible across the Workbook How to create a global variable? global variable for all controller and views How to define global variable in Google Apps Script How to modify a global variable within a function in bash? Using a global variable with a thread Is it possible to use global variables in Rust? How to access global js variable in AngularJS directive

Examples related to local

Load local images in React.js Access to Image from origin 'null' has been blocked by CORS policy How can I parse a local JSON file from assets folder into a ListView? How to make a local variable (inside a function) global How to securely save username/password (local)? Is it possible to run .php files on my local computer? How to keep the local file or the remote file during merge using Git and the command line? Mocking methods of local scope objects with Mockito Load HTML file into WebView PHP server on local machine?