-3

I was wondering if you can make a function inside of another function in python. Just like this:

f().f2()

The f() is the first function, and f2() is the second function. Say f().f2() prints out "Hello world". But if I change the .f2() to .f3() it will print another string of text.

Is it possible?

martineau
  • 119,623
  • 25
  • 170
  • 301
Rydex
  • 395
  • 1
  • 3
  • 9

4 Answers4

2

Here's one approach:

def f():
    class F:
        @staticmethod
        def f2():
            print("Hello world")

        @staticmethod
        def f3():
            print("Another string of text")
    return F


f().f2()
f().f3()
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • 1
    Yes, it works. But I think we should question OPs rational as it feels like an XY problem. – DeepSpace Oct 18 '21 at 13:56
  • Wonderful! the benefit of doing this is that your IDE can offer auto-completion hints apparently. – rv.kvetch Oct 18 '21 at 13:59
  • 3
    @rv.kvetch And the downside is that `F` will be redefined every single time `f` is called, which can have a high overhead – DeepSpace Oct 18 '21 at 14:01
2

The other answers are good, but a simpler solution would be to make f a class. Since classes are callable, you can basically treat them as functions. The dot in f().f2() implies that f must return an object with an f2 attribute, and a class can do just that:

class f:

    def f2(self):
        print("Hello world")

    def f3(self):
        print('another string of text')
luther
  • 5,195
  • 1
  • 14
  • 24
1

I like Samwise answer better, but here's a way of doing it without classes, if you really wanted to:

def f():
    def f2():
        print("Hello world")

    def f3():
        print("Another string of text")

    for func_name, func in locals().items():
        setattr(f, func_name, func)

    return f


f().f2()
f().f3()
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53
0
def f():
    class F:
        @staticmethod
        def f_2():
            print("something")

        @staticmethod
        def f_3():
            print("something 2")
    return F


f().f_2()
f().f_3()
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Marko
  • 123
  • 1
  • 10