Skip to content Skip to sidebar Skip to footer

Calling A Variable In A Different Function Without Using Global

I'm trying to use a variable / list in a function that is defined in another function without making it global. Here is my code: def hi(): hello = [1,2,3] print('hello') d

Solution 1:

You need to return hello from your hi method.

By simply printing you are not able to gain access to what happens inside the hi method. Variables created inside a method remain within the scope of that method.

Information on variable scope in Python:

http://gettingstartedwithpython.blogspot.ca/2012/05/variable-scope.html

You return hello inside your hi method, then, when you call hi, you should store the result in a variable.

So, in hi, you return:

def hi():
    hello = [1,2,3]
    return hello

Then when you call your method, you store the result of hi in a variable:

hi_result = hi()

Then, you pass that variable to your bye method:

bye(hi_result)

Solution 2:

if you don't want to use a global variable, your best option is just to call bye(hello) from within hi().

def hi():
    hello = [1,2,3]
    print("hello")
    bye(hello)

def bye(hello):
    print(hello)

hi()

Solution 3:

You cannot declare global variables inside a function without global.You can do this

def hi():
    hello = [1,2,3]
    print("hello")
    return hello

def bye(hello):
    print(hello)

hi()
bye(hi())

Solution 4:

As others have said, it sounds like you're trying to solve something that would be better off done a different way (see XY problem )

If hi and bye need to share different types of data, you might be better off using a class. Ex:

classMyGreetings(object):
    hello = [1, 2, 3]

    defhi(self):
        print('hello')

    defbye(self):
        print(self.hello)

You could also do it with globals:

global hello

defhi():
    global hello
    hello = [1,2,3]
    print("hello")

defbye():
    print(hello)

or by having hi return a value:

def hi():
    hello = [1,2,3]
    print("hello")
    returnhello

def bye():
    hello = hi()
    print(hello)

or you could have hi put hello on the hi function itself:

def hi():
    hello = [1,2,3]
    print("hello")
    hi.hello = hello


def bye():
    hello = hi.hello
    print(hello)

Now that said, the sketchy way to accomplish what you're asking would be to pull out the source code of hi(), and execute the body of the function within bye() and then pull out the variable hello:

import inspect
from textwrap import dedent


defhi():
    hello = [1,2,3]
    print("hello")

defbye():
    sourcelines = inspect.getsourcelines(hi)[0]
    my_locals = {}
    exec(dedent(''.join(sourcelines[1:])), globals(), my_locals)
    hello = my_locals['hello']
    print(hello)

Post a Comment for "Calling A Variable In A Different Function Without Using Global"