Reputation: 117
I want to do the following in python:
def func1():
var1 = "something"
def func2():
print var1
What is the correct mode to do this ? I've not found in documentation at all
PS. If possible, it's not my plan to make that 'var1' a global variable.
Thanks.
Upvotes: 4
Views: 26212
Reputation: 9
You could try:
filename.py:
def func1():
var1 = "something"
def func2():
var = __ import__('filename').var1
print var
Upvotes: 0
Reputation: 95712
I assume you don't want to pass the variable as a parameter between the function calls. The normal way to share state between functions would be to define a class. It may be overkill for your particular problem, but it lets you have shared state and keep it under control:
class C:
def func1(self):
self.var1 = "something"
def func2(self):
print self.var1
foo = C()
foo.func1()
foo.func2()
Upvotes: 7
Reputation: 610
You could try something like
def func1():
var1 = "something"
return var1
def func2():
print func1()
If you need func1 to do more things than just define var1, then maybe what you need is to define a class and create objects? See http://docs.python.org/tutorial/classes.html
Upvotes: 0
Reputation: 82048
No, it is not possible to do things like that. This is because of something called "scope". You can either create a module-level variable or place it in an OOP construct.
Upvotes: 4
Reputation: 6613
Well your func2() is trying to print a variable in the scope of another function. You can either
Upvotes: 0