Simão
Simão

Reputation: 117

Learning Python: print variable inside a function from another function

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

Answers (5)

Steven Garcia
Steven Garcia

Reputation: 9

You could try:

filename.py:


def func1():
     var1 = "something"

def func2():
     var = __ import__('filename').var1
     print var

Upvotes: 0

Duncan
Duncan

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

Nick Edwards
Nick Edwards

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

cwallenpoole
cwallenpoole

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

Dimitry
Dimitry

Reputation: 6613

Well your func2() is trying to print a variable in the scope of another function. You can either

  • Return the value of var1 when calling func1 (eg. def func2(): print func1() }
  • Call func2 from func1 and pass the value of var1

Upvotes: 0

Related Questions