Yuval Meshorer
Yuval Meshorer

Reputation: 166

Call a nested function in Python

Is it possible to call a nested function defined inside an existing function:

For example:

def first(x):
    def second():
        print(x)
    return second

I know I can do something like this: first(10)()

Yet I want to do something similar to this:

first(10).second()

My thinking is that it is not possible because second does not exist until first is called.

Am I right?

Upvotes: 2

Views: 4020

Answers (3)

Davis Herring
Davis Herring

Reputation: 40063

If you want, you can return several functions that way:

class Box(object):
    def __init__(self,**kw): vars(self).update(kw)
def first(x):
    def second():
        print(x)
    def third(y): return x+y
    return Box(second=second,third=third)

first(10).second()   # prints 10
x=first(15)
x.second()           # prints 15
print(x.third(10))   # prints 25

Any resemblance to reputation scores for answers is coincidental.

Upvotes: 4

Shoaib Zafar
Shoaib Zafar

Reputation: 312

Though it is not the right way but just for fun. What you are doing here is returning the instance of the second function, so while calling it, no dont need to call it by name, jsut use the variable.

def first(x):
    def second():
        print(x)

    return second

x = first(10)
x()

or like this

first(10)()

as mention by other, use class instead.

Upvotes: 1

Arthur Tacca
Arthur Tacca

Reputation: 10038

Why not use a class?

class First:
    def __init__(self, x):
        self.x = x

    def second(self):
        print(x)

First(3).second()

The fact that all Python functions are closures is a great feature, but it's fairly advanced. Classes are the usual place to store state.

Upvotes: 2

Related Questions