loading...

Can I create new functions for parameters in Python?

twitter logo github logo ・1 min read

I am not new to Python, and currently I am on the latest release (3.9.0) and to my knowledge the answer is "No". But is there anything I am missing? If I am being confusing the JS equivalent would be:

function example(func) {
    func()
}
example(function() {
    alert("hi")
})

so in Python can I do:

def example(func):
    func()
example("""some way to declare a function here""")

instead of:

def example(func):
    func()
def myFunc():
    print("hi")
example(myFunc)

?
Thanks!
Cheers!

twitter logo DISCUSS (3)
markdown guide
 

In addition to David’s answer, you can also use decorators if you wanna do something with the function when assigning it, like this:

def dec(func):
    func()
    return func

# dec will be called with test as a parameter, which will then be set to the return value.
@dec
def test():
    print(β€œHello, world!”)

You can even give it other parameters by taking those like normal, and instead returning a function that takes the decorated function, like this:

def dec(string):
    def dec_inner(func):
        func(string)
        return func
    return dec_inner

# dec will be called with β€œHello, world!”, and the returned function will be called with test, and test will be set to whatever that returns.
@dec(β€œHello, world!”)
def test(string):
    print(string)
 
 

Lambda is the rough equivalent.

example(lambda : print("hi")) 

but lambda is used much less in python than anonymous functions in javascript.

Classic DEV Post from Apr 30 '19

Who's looking for open source contributors? (April 30th edition)

PDS OWNER CALIN (Calin Baenen) profile image
I am a 13 (as of Oct 30 of 2019) yr/o developer (I have been developing mini-projects for 4, years now, since I was 9), who makes projects in languages like: Java, HTML, Python 3, JS, CSS, and C#.