Search code examples
pythonfunctionvariablesgloballocal

Is it possible to take the Local Variable of a Function and convert it to a Global Variable or use it in an other Function


I'd like to know, If I can use the Local Variable of a Function (I'll call it for now Fct.1) in an other Function (Fct.2) (so that a variable in Fct.2 is assgined the same value of a Variable in Fct.1) or if it's possible to convert automatically a Local Variable into a Global Variable.

For example:

def fct1(a):
    example = 10 * a

fct1(10)


def fct2():
    something = example * 2

What I want to do is use the example Variable in Fct1 in Fct2.

Is that possible?

I hope you can help me.


Solution

  • There are a few ways in Python through which you can manipulate global and local variables of different objects from other objects. Most of those are advanced coding and some include fiddleing with Python interpreter mechanisms. However, what you want is quite simple:

    some_global_var = None # Declare the global variable outside of both functions in advance
    
    def f1 (a):
        global some_global_var
        some_global_var = a*10
    
    def f2 (a):
        return some_global_var*a
    

    Note that global variables are accessible for read from a function, but unless you declare it as global at the top of your function, assigning a value to it will just make a local variable with the same name, and the global one will be left alone.

    There are good reasons for that, some of which are already pointed out in the other answer.

    To do the same thing, but much more acceptable would be to use objects:

    class Math:
        some_attribute = None
        def f1 (self, a):
            self.some_attribute = a*10
    
        def f2 (self, a):
            return self.some_attribute*a
    m = Math()
    m.f1(10)
    print(m.f2(20))
    

    Perhaps you may want to learn objective oriented programming for your project. It is usually the solution when functions need to share resources in a way you asked for.

    Some programmers are positively afraid of global variables and are trying to avoid them at all costs. That's because they are very bad at debugging and, in short, are bad programmers.

    Using them is a bit tricky because you must always keep track of your global variables and what is happening to them, and where, in order not to make any mistakes. This can be especially nasty for big projects in low-level programming languages like C. But sometimes they are simply unavoidable and you would make a bigger mess by avoiding them. To help you remember what you are dealing with Python has the keyword global.

    Your case though is not exactly one where you would use a global variable. But you must decide. When you use them, make sure that they are used for exactly one purpose and avoid using the same name for local variables anywhere else and you will be fine. Also, minimize the number of functions that are allowed to actually change them.