1

I know that the order of functions in a script doesn't matter. However, this sample code doesn't work:

main.py

_FUNCTIONS = (_foo, _bar) 

def myfunc():
    for f in _FUNCTIONS:
        print(f())

def _foo():
    return False

def _bar():
    return True

myfunc()

provides the following error

File "main.py", line 1, in <module>
    _FUNCTIONS = (_foo, _bar) 
NameError: name '_foo' is not defined

However, if I don't use _FUNCTIONS and inject (_foo, _bar) into a code this will work:

def myfunc():
    for f in (_foo, _bar):
        print(f())

def _foo():
    return False

def _bar():
    return True

myfunc()

Why the first example doesn't work?

How can I extract the list of functions in a variable and put it on the top of the script?

Dejan
  • 966
  • 1
  • 8
  • 26
  • 6
    "I know that the order of functions in a script doesn't matter."—Yeah it does. You can't store a reference to something before it is defined. – khelwood Jun 07 '21 at 15:12
  • in the second code snipped, the function is executed *after* the variables are defined. Try running `myfunc()` directly after the definition of `myfunc` and it will fail like the first code snippet. – FObersteiner Jun 07 '21 at 15:14
  • 1
    Think about the order of execution, not the order of the statements themselves. Python will make an initial pass through your file, executing each statement at the top level. The `def` statements will define a function, but not execute it. By the time you get to the `myfunc()` call, all the functions are defined. In your first example, you're using `_foo` and `_bar` before their `def`s have been seen. – Mark Ransom Jun 07 '21 at 15:19

1 Answers1

2

You actually misunderstood it, When you are using _FUNCTIONS = (_foo, _bar) , python expects _foo and _bar as a variable nothing fancy here, and since you haven't defined any reference to it yet, it's undefined, thus throws error.

In the second case, you're doing the same thing inside a function, by that time, the function is already available in python's scope, thus no error.

And as @khelwood has mentioned in the comment, the order does matter

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
  • 1
    You are right. I misunderstood that a constant is evaluated at the time of it's definition, not at the time when we actual use it (like in case of functions). – Dejan Jun 07 '21 at 16:16