Reputation: 77
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")
def bye(hello):
print(hello)
hi()
bye(hello)
At the moment I am getting the error that "hello" in "bye(hello)" is not defined.
How can I resolve this?
Upvotes: 5
Views: 3490
Reputation: 2137
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:
class MyGreetings(object):
hello = [1, 2, 3]
def hi(self):
print('hello')
def bye(self):
print(self.hello)
You could also do it with globals:
global hello
def hi():
global hello
hello = [1,2,3]
print("hello")
def bye():
print(hello)
or by having hi return a value:
def hi():
hello = [1,2,3]
print("hello")
return hello
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
def hi():
hello = [1,2,3]
print("hello")
def bye():
sourcelines = inspect.getsourcelines(hi)[0]
my_locals = {}
exec(dedent(''.join(sourcelines[1:])), globals(), my_locals)
hello = my_locals['hello']
print(hello)
Upvotes: 0
Reputation: 26578
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)
Upvotes: 5
Reputation: 20339
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())
Upvotes: 2
Reputation: 1926
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()
Upvotes: 3