0

The function hoisting in javascript allows us to do this thing, which is awesome to the code readability:

function f(a,b){
    return divide(a,b)*a
    
    function divide(a,b){
        return a/b
    }
}

Haskell allows us to do something like this with the "where". Does python has any syntax mechanism that allows this?

vitorfigm
  • 13
  • 1
  • Does this answer your question? [Declare function at end of file in Python](https://stackoverflow.com/questions/3754240/declare-function-at-end-of-file-in-python) – ChrisGPT was on strike Dec 13 '20 at 04:15
  • I don't think this is really a duplicate of that question, although the solution does apply - however, where defining a `main()` and calling it at the end is a common pattern in Python, doing it in a function is a bad idea, as shown below. – Grismar Dec 13 '20 at 04:26

1 Answers1

0

There's no hoisting of the type you're looking for.

Python does some hoisting, for example variables that are declared in a block (like the for loop variable) are hoisted to the scope the block is in.

But you cannot reference a variable (or other name, like a function) before it has been assigned or defined.

If you want to have that order of code, this a way around it, but it hardly helps readability:

def f(a, b):
    def _f():
        return divide(a, b)*a

    def divide(a, b):
        return a / b
    return _f()


print(f(10, 5))
}

More in general, don't try to force the conventions of one language on another - use the language that has the conventions you like, or learn the conventions of the language you use. Other coders reading your code (including future you) will thank you.

Grismar
  • 27,561
  • 4
  • 31
  • 54