Python Forum
function defined in a function
Thread Rating:
  • 2 Vote(s) - 2 Average
  • 1
  • 2
  • 3
  • 4
  • 5
function defined in a function
#1
if a function is used only by another function, do you ever define it inside the function that uses it (before it is used)?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
You can get some ideas by reading this: Python Inner Functions—What Are They Good For?
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
(Jul-19-2018, 06:13 AM)perfringo Wrote: You can get some ideas by reading this: Python Inner Functions—What Are They Good For?
well, in my opinion this is very poor tutorial if I may disagree with most of the examples and 'reasons' apart from Closures and Factory Functions.
Quote:Encapsulation:
You use inner functions to protect them from everything happening outside of the function, meaning that they are hidden from the global scope.
well, even defined in the global scope, the function has it's own scope and is protected enough. And even as an inner function, it still has access to global scope if coder does not use encapsulation properly

my_global = 'test'

def foo():
    def bar():
        print(my_global)
    bar()
    
foo()
Probably I may hide a function better if it is a function defined in function defined in function and so on? LOL

Even the author admits that
Quote:Note: Keep in mind that this is just an example. Although this code does achieve the desired result, it’s probably better to make inner_increment() a top-level “private” function using a leading underscore: _inner_increment().

then in the recursion example
def factorial(number):

    # Error handling
    if not isinstance(number, int):
        raise TypeError("Sorry. 'number' must be an integer.")
    if not number >= 0:
        raise ValueError("Sorry. 'number' must be zero or positive.")

    def inner_factorial(number):
        if number <= 1:
            return 1
        return number*inner_factorial(number-1)
    return inner_factorial(number)
why on earth would you define another function? Just to make it more obscure?

Keepin’ it DRY
Well, DRY goal is achieved even if the inner function is defined in the global scope. So it doesn't make difference. And again, author admits
Quote:Note: Again, it is common to just make do_stuff() a private top-level function, but if you want to hide it away as an internal function, you can.
Again hide away... Wall

Not to mention constant use of type checking anti-pattern all over the examples
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
I am not qualified to judge this tutorial. However, explanation in this tutorial was enough for me:

Quote:Now we come to the most important reason to use inner functions. All of the inner function examples we’ve seen so far have been ordinary functions that merely happened to be nested inside another function. In other words, we could have defined these functions in another way (as discussed). There is no specific reason for why they need to be nested.

But when it comes to closures, that is not the case: you must use nested functions.

I understood that everything prior to that was just throwing in some examples of inner functions to get grasp what it is about. Everything after that was 'real' stuff.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#5
I do this occasionally, both in Python as well as Scala. I missed the feature when I was writing Java regularly.

(Jul-19-2018, 07:15 AM)buran Wrote: then in the recursion example [...] why on earth would you define another function? Just to make it more obscure?
That's a decent example of when I might use it. You don't need to do the validation for each recursive call, so that pattern makes sure it's only done once. I also use it to aid recursion when I want to use an additional parameter as an "accumulator" or some start value but don't want to expose that extra parameter to callers, since it's an implementation detail.

Even in Scala where I'm more likely to pass a function to another function or even do recursion manually, inner-functions aren't something I do terribly often, but I appreciate having the option.
Reply
#6
i have been managing a lot of code as files of functions. some of them need other function only they call (a part) of their work. i have been looking for ways to organize files with multiple functions. one thing i wonder now is the effect of importing a function with the import statement in a function.

why is the name "closure" used for this concept?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#7
(Jul-20-2018, 07:38 AM)Skaperen Wrote: why is the name "closure" used for this concept?

Because of __closure__ property? Smile

Understanding Python's closures

Now, where did __closure__ property come from.....
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#8
It's called a closure because of the associated environment. The inner function includes the bindings of any variables that were local to the outer function, even after the inner function leaves that scope. Those open references in the inner function are closed by the associated environment.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#9
this "closure" concept appears to be quite broadly used, in computer science, not just languages and not just Python. i recall it in some other things i tried to learn, and it being there was often the reason i could not understand those things. if i had encountered them in Python way earlier, i might still be doing stuff in C.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#10
Closures are great. I like to remember what they are by thinking of a function who's scope "closes over" it's parent's scope.

It's sort of like how a class's method has access to the enclosing scope, via the self parameter. They're used all over the place in javascript (like, ALL over the place), but in Python pretty much the only place I see them commonly used is for function decorators.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  function defined inside a function Skaperen 2 2,402 May-13-2021, 01:04 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020