3

Given a function within a function, how do I call the inner function from an external function?

ex.

def a():
    print 'a'
    def b():
        print 'b'
        def c():
            print 'c'

def d():
    # how would I now call a, b and c from here?
    def e():
        # how would I call a, b and c from here as well?

Yes I know it's horrible code structure and should not be done - but how do you do it?

Edit: Any way to do this using decorators?

2
  • You can do it by using class instead of def. What on earth can your use case be? Commented Aug 20, 2012 at 5:25
  • 1
    @BurhanKhalid, it's not quite impossible, but certainly not something you should do Commented Aug 20, 2012 at 5:27

4 Answers 4

8

You cannot. b and c are local variables inside a and do not exist except while a is executing.

(Since these are constants, you can technically access them via a.__code__.co_consts, but this is not a real solution even if you're okay with horrible code structure. You would have to execute the function with exec and you can't pass arguments to it.)

Sign up to request clarification or add additional context in comments.

2 Comments

And, this is indeed one of the techniques that are used to create absolute private attributes in Python.
@behnam Can you give an example of where absolute private attributes is used in a python program? I'm curious as to why it's necessary, and the actual implementation.
3

You can't, since those functions are created when the outer function is called, and are destroyed when the outer function exits. You would need to put a reference to the inner function somewhere persistent if you wanted to access them from elsewhere.

2 Comments

You could, for example, return these references from the outer function.
I don't want to post this as an answer because no one should get karma for something so perverse, but the obvious place to stash the references is in the function itself.. adding b.c = c and a.b = b after the function declarations would enable a.b.c().. (shudder)
1

With this structure, you can only call a() in the two places you indicated. b() is only defined while a() runs, and c() is only defined while b() runs. a() can be called from anywhere since it defined globally.

For example:

def a():
    print 'a'
    def b():
        print 'b'
        def c():
            print 'c'

def d():
    # how would I now call a, b and c from here?
    a()
    def e():
        a()
        # how would I call a, b and c from here as well?

d()

results in

a

(Similarly, e() is only defined when d() is running. d(), like a(), is defined globally.)

Comments

0

You can change your outer function so it will return your inner function

Comments

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.