0
def out():
   var1 = "abc"
   print(var1)

   def inner():
      var2 = "def"

I want to call only "Inner" function... the final output should print only var2 not var1...

Thank you in advance

3
  • You'll have to move inner() and add a print call for var2. This is unrelated to django and tkinter btw. Commented Apr 6, 2017 at 7:53
  • Why dont you have just two different functions? is it some requirement in your project? Commented Apr 6, 2017 at 7:54
  • How can you want var2 to be printed when you have no print(var2)? How do you want to call the function if you don't even return it in any way? Please, clarify your question. Commented Apr 6, 2017 at 8:01

3 Answers 3

1

If you don't want to run some part of the function 'out' you could use parameters.

def out(choice=True):
  if choice :
    var1 = "abc"
    print(var1)
 else :
    def inner():
       var2 = "def"
       print(var2)
    inner()
Sign up to request clarification or add additional context in comments.

Comments

0

You will not be able to call inner from outside the out function, since inner is only defined inside out, unless you create a reference to inner from outside the out function. In addition, inner is not outputting anything since it does not have a print statement.

To combat this, you have two options:

  • Place inner in a broader scope (i.e. outside out) and add to it a print(var1) statement.
  • If it is required to have the inner function be inside out then just return inner as a closure from out, with the print statement also inside inner; or just call it from inside out. This has a side-effect of also executing whatever statements are inside out up to returning the closure.

1 Comment

"You will not be able to call inner from outside the out function" <- Well technically it is possible to force the outer function to create a reference to the inner function in globals() on its first call. It's just not something you ever want to do.
0

The method your trying is called as nested functions:

You can chek this answer for information about nested function in Python.

Some other information about closure

Another method is,

def fun1():
    x = 11
    def fun2(a=a):
        print x
    fun2()

fun1()

Output:

prints 11

Example 2:

def f1(x):
    def add(y):
        return x + y
    return add

res = f1(5)
print(res(10))  # prints 15

2 Comments

Your first example is wrong. It gives an error saying a is undefined. Also, a colon is needed at the end of 'def fun2(a=a)'.
I missed the colon didnt notice that.. Would you provide the logs of undefined, I explained here the usage of inner functions in python.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.