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

Can global variable be passed into Python function?

On Friday, February 21, 2014 12:37:59 AM UTC-6, Sam wrote:
> I need to pass a global variable into a python function. However, the global variable does not seem to be assigned after the function ends. Is it because parameters are not passed by reference? How can I get function parameters to be passed by reference in Python?

def  func(x):
    global  ref_name
    ref_name = '3.14159'
    # rest of the code
    # rest of the code

When you call this function the ref_name  reference will be set to '3.14159' as a string and your main code will be able to 'see' it, and other funcs will be able to 'see' it too... play with it a bit...  if other funcs need to write to it they will also have to use the   global ref_name  line.  As long as other funcs only read the reference, then the global line is not needed to 'see' the reference.

As others have noted, python does not have a 'variable' concept (references to objects instead) and so your question is a little ambiguous. 

Also, using global references within functions is not a good idea... generally speaking.